2016-11-04 31 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

你是对的。你的假设和我一样可能。无论如何,我提出了你的答案,因为它显示了另一种可能的选择。 –

相关问题