在这段代码中,undefined 是什么意思?没有指定未定义它说“我的名字是未定义的,我是一个未定义的”
(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");
}());
最佳答案
我的回答假设 Without specifying undefined
你的意思是这样的调用:
theFunction.apply(["ali", "Developer"]);
当您使用call
或apply
时,第一个参数是执行上下文(theFunction
中的变量this
).这两个示例将其设置为 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未定义”
call
和 apply
通常在您想要更改函数的执行上下文时使用。您可能正在使用 apply
将参数数组转换为单独的参数。为此,您需要将执行上下文设置为与调用函数时未应用时相同的执行上下文:
theFunction("John", "fireman"); // `this` points to `window`
theFunction.apply(this, ["John", "fireman"]); // `this` points to `window`
关于javascript - javascript函数原型(prototype)中undefined指的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40430243/