【问题标题】:What does undefined refer to in javascript function prototypejavascript函数原型中的undefined指的是什么
【发布时间】:2017-03-18 17:37:27
【问题描述】:

在这段代码中,未定义是什么意思?没有指定 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");
}());

【问题讨论】:

  • 请参阅:stackoverflow.com/questions/5247060/… 这样您就不会更改 this 的值。
  • “如果不指定 undefined,它会说“我的名字是未定义的,我是未定义的”” 在哪里?
  • 我认为OP的意思是,如果他在使用apply或call时不添加undefined作为第一个参数。正确答案如下。

标签: javascript call apply


【解决方案1】:

我的回答假设 Without specifying undefined 你的意思是这样的电话:

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

当您使用callapply 时,第一个参数是执行上下文(theFunction 内的变量this)。这两个示例将其设置为undefined,因此this 内的theFunction 将评估为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`

【讨论】:

  • this 从未在任何地方使用过,并且代码输出的不是 OP 所说的那样。
  • 我想说,一些代码会解释更多,但你打败了我 :)
  • OP 在问题的javascript 不使用theFunction.apply(["ali", "Developer"])。虽然 OP 可能已经尝试过 theFunction()
  • 好的,我现在明白“不指定未定义”是什么意思了。他们发布了指定未定义的代码,并质疑未指定未定义的结果。那么这个答案是正确的。
  • @timenomad,感谢您的建议,并在问题底部添加了说明
【解决方案2】:

虽然theFunction() 不包括在尝试的调用之一中,但theFunction() 再现了问题中描述的结果

没有指定 undefined 它说“我的名字是未定义的,我是 未定义”

即不传参数调用theFunction();当theFunction 被调用时,这将是预期的结果,其中nameprofession 在函数体内是undefined

(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");

}());

【讨论】:

  • 此调用 theFunction.apply(["ali", "Developer"]); 将产生 OP 得到的结果 My name is undefined and I am a undefined .
  • @Maximus 编辑答案;尽管theFunction()theFunction.apply(["ali", "Developer"]) 都没有包含在OP 实际尝试的内容中。问题中列出的调用均未返回问题中描述的结果。
  • 你是对的。你的假设和我的一样。无论如何,我赞成你的回答,因为它显示了另一种可能的选择。
猜你喜欢
  • 2019-06-05
  • 2011-01-21
  • 2013-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多