javascript - javascript函数原型(prototype)中undefined指的是什么

标签 javascript call apply

在这段代码中,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"]);

当您使用callapply 时,第一个参数是执行上下文(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"],以及 nameprofession 被评估为 undefined 因为您只将一个参数传递给 apply,这就是为什么您得到 "My name is undefined and I am a未定义”

callapply 通常在您想要更改函数的执行上下文时使用。您可能正在使用 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/

相关文章:

javascript - 从不同的节点插件方法多次调用 JS 函数

javascript - 使用ajax动态分割滚动条

R sapply is.factor

r - 查找向量中下一个更高值之前的值的数量

javascript - 实例化 JS 对象,该对象从字符串名称中获取参数数组

JavaScript - 映射、过滤、缩减。从数组转换为更深层次的树

batch-file - 如何调用从当前目录向上一级的批处理文件?

Ruby 卡住方法

在 charCodeAt 上使用的 Javascript 应用或调用

python - Pandas 应用函数将多个值返回到 Pandas 数据框中的行