2016-11-04 32 views
1

在這段代碼中undefined是什麼意思?如果不指定不確定它說:「我的名字是不確定的,我是一個不確定的」undefined在javascript函數原型中引用了什麼

(function(){ 
 
    'use strict'; 
 

 
    function theFunction(name, profession) { 
 
     console.log("My name is " + name + " and I am a " + profession + " . "); 
 
    } 
 
    theFunction("John", "fireman"); 
 
    theFunction.apply(undefined,["ali", "Developer"]); 
 
    theFunction.call(undefined, "sara", "doctor"); 
 
}());

+0

參見:http://stackoverflow.com/questions/5247060/in-javascript-is-there-equivalent-to-apply-that-doesnt-change-the-value-這是因爲你不會改變'this'的價值。 – scrappedcola

+1

_「沒有指定未定義它說」我的名字是未定義的,我是一個未定義的「」_哪裏? – guest271314

+0

我認爲OP的意思是,如果在使用apply或call時他沒有添加'undefined'作爲第一個參數。正確答案如下。 –

回答

6

我的回答假設由Without specifying undefined你的意思是這樣的一個電話:

theFunction.apply(["ali", "Developer"]); 

當您使用callapply,第一個參數是執行上下文(變量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"],並nameprofession被評估爲undefined,因爲你只有一個參數傳遞給apply,這就是爲什麼你'正在獲取"My name is undefined and I am a undefined"

callapply通常用於想要更改函數的執行上下文。您可能使用apply將參數數組轉換爲單獨的參數。要做到這一點,你需要設置爲一個本來如果你不申請調用的函數相同的執行上下文:

theFunction("John", "fireman"); // `this` points to `window` 
theFunction.apply(this, ["John", "fireman"]); // `this` points to `window` 
+2

這個''在任何地方都不會被使用,代碼的輸出不是OP所說的。 – GSerg

+0

我會說,有些代碼會解釋更多,但你打敗了我:) –

+0

OP在'javascript'問題處不使用'theFunction.apply([「ali」,「Developer」])''。雖然OP可能已經嘗試過'函數()' – guest271314

1

雖然theFunction()不作爲其中一個呼叫嘗試,theFunction()抄錄結果描述在問

不指定不確定它說:「我的名字是不確定的,我是一個 未定義」

就是叫theFunction()而不通過參數;當theFunction被調用時,nameprofessionundefined在函數體內的預期結果。

(function() { 
 
    'use strict'; 
 

 
    function theFunction(name, profession) { 
 
    console.log("My name is " + name + " and I am a " + profession + " . "); 
 
    } 
 
    theFunction(); // logs result described at Question 
 
    theFunction("John", "fireman"); 
 
    theFunction.apply(undefined, ["ali", "Developer"]); 
 
    theFunction.call(undefined, "sara", "doctor"); 
 

 
}());

+0

這個調用'theFunction.apply([「ali」,「Developer」]);'會產生OP得到的結果'我的名字是未定義的,我是一個未定義的。 ' –

+0

@Maximus編輯答案;雖然'theFunction()'和'theFunction.apply([「ali」,「Developer」])不包括在OP實際嘗試的內容中。問題中列出的問題沒有任何回答結果。 – guest271314

+0

你是對的。你的假設和我一樣可能。無論如何,我提出了你的答案,因爲它顯示了另一種可能的選擇。 –

相關問題