我的回答假設由Without specifying undefined
你的意思是這樣的一個電話:
theFunction.apply(["ali", "Developer"]);
當您使用call
或apply
,第一個參數是執行上下文(變量this
內部theFunction
)。這兩個示例將其設置爲undefined
,因此在theFunction
之內的this
將評估爲undefined
。例如:
function theFunction(name, profession) {
console.log(this); // logs `undefined`
console.log("My name is " + name + " and I am a " + profession + " . ");
}
theFunction.apply(undefined, ["ali", "Developer"]);
Here is線程解釋爲什麼人會使用undefined
作爲執行上下文。
現在,你的問題。如果您在通話省略undefined
是這樣的:
theFunction.apply(["ali", "Developer"]);
執行上下文 - this
- 設置爲["ali", "Developer"]
,並name
和profession
被評估爲undefined
,因爲你只有一個參數傳遞給apply
,這就是爲什麼你'正在獲取"My name is undefined and I am a undefined"
call
和apply
通常用於想要更改函數的執行上下文。您可能使用apply
將參數數組轉換爲單獨的參數。要做到這一點,你需要設置爲一個本來如果你不申請調用的函數相同的執行上下文:
theFunction("John", "fireman"); // `this` points to `window`
theFunction.apply(this, ["John", "fireman"]); // `this` points to `window`
參見:http://stackoverflow.com/questions/5247060/in-javascript-is-there-equivalent-to-apply-that-doesnt-change-the-value-這是因爲你不會改變'this'的價值。 – scrappedcola
_「沒有指定未定義它說」我的名字是未定義的,我是一個未定義的「」_哪裏? – guest271314
我認爲OP的意思是,如果在使用apply或call時他沒有添加'undefined'作爲第一個參數。正確答案如下。 –