function name(){
var fullName = "lawrence Turton";
function concat(name){
return "Hello Mr. " name;
};
return concat(fullName);
}
我目前正在學習javascript。示例代碼來自我正在觀看的 youtube 教程,課程是關于在函式內嵌入函式,第一個函式名為“name”,然后嵌入函式 concat 的引數也是“name”,然后回傳值是 return concat(fullName );<--- 這部分真的讓我感到困惑,因為他在為第一個函式和第二個函式命名時使用了三次“名稱”作為 concat 函式的引數,在連接字串中使用了第三個,并且由于var fullName = "lawrence Turton" 是在 fullName 變數名中定義的,我找不到 "lawrence Turton"(string) 和 "name"(parameter)(variable) 之間的明確聯系,
我的問題是,為什么函式 concat 中的引數不能是 (fullName),因為“lawrence Turton”已經在變數 FullName 中定義。
為什么不這樣寫
function name(){
var fullName = "lawrence Turton";
function concat(fullName){
return "Hello Mr. " fullName;
};
return concat(fullName);
}
我也試過這個,它奏效了
uj5u.com熱心網友回復:
為什么不能這樣寫
正如您可能已經發現的那樣,您可以。但建議您避免使用它。
為什么?你可能會問。好吧,你應該知道在你的函式內部concat,識別符號“ fullName”指的是函式引數而不是fullName在外部作用域上宣告的變數,這可以稱為“變數陰影”,它不被認為是一個好的做法(因此我們盡量避免它)。
如果您愿意學習 JS,您肯定會遇到某個“范圍”主題,因為它是該語言的支柱之一。您可以在W3Schools: JavaScript Scope上對其進行簡短閱讀,但我強烈建議您在開始學習 JS 時深入研究它。
你可以在這里更深入地閱讀它(你還不知道 JS:Scope & Closures,Kyle Simpson)。
uj5u.com熱心網友回復:
代碼示例并不是那么好,因為該函式沒有按照它所說的去做。
它被稱為 name,但它回傳對 name 的問候。
此外,您還可以回憶.concat()在訊息的末尾添加更多內容。
function name() {
var fullName = "lawrence Turton";
function concat(name) {
return "Hello Mr. " name;
}
return concat(fullName);
}
console.log(name());
console.log(name().concat("more stuff at the end."));
將函式用作方法會更有意義,因此它們可以做更多的事情。
在下面的示例中,我們可以通過呼叫.greet()來獲取問候語,或使用 更改用戶名.setName()。
如果您查看回傳的函式,我們會使用箭頭函式和匿名函式。這是因為在 setName 中,我們想要回傳this背景關系,因此我們可以鏈接方法。這讓我們可以做到user.setName(name).greet()。使用箭頭函式,this作業方式不同,作業方式也不同。
這是更多詳細資訊的鏈接:此差異
const createUser = (username) => ({
greet: (greeting) => {
if(greeting) return greeting username;
return `Hi, ${username}`
},
setName: function(_username){
username = _username;
return this;
},
})
const user = createUser("John Smith");
console.log(user.greet())
user.setName("Fred")
console.log(user.greet())
console.log(user.setName("Steve").greet())
此功能類似于類。對于一個類,它看起來像這樣:
class User {
// the constructor is ran when you initialize the class.
constructor(username){
this._username = username;
}
greet(greeting){
if(greeting) return greeting this._username;
return `Hi, ${this._username}`;
}
setName(name){
if(name) this._username = name;
return this;
}
}
// You have to have new to create a new instance of the class.
const user = new User("John Snow");
console.log(user.greet());
user.setName("John Wick");
console.log(user.greet())
console.log(user.setName("John Smith").greet())
您可以使用您喜歡的任何版本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358027.html
標籤:javascript 功能
