我的回答假设由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'作为第一个参数。正确答案如下。 –