Javascript "apply" 函数似乎不适用于全局 "this"?

Javascript "apply" function seems not working for global "this"?

我在nodejs中测试了'this'关键字的范围:

color = 'red';
var o = {
    color: 'blue'
};

function say() {
    console.log(this.color);
};
say.apply(this);  //'undefined'
say.apply(global);//'red'

在浏览器中:

color = 'red';
var o = {
    color: 'blue'
};

function say() {
    alert(this.color);
};
say.apply(this);  //'undefined'
say.apply(window);//'red'

var color = 'red';
function say() {
  alert(this.color);
}
say.apply(this);   //'red'
say.apply(window); //'red'

结果对我来说有点奇怪:只要"this"是指向"global"或"window"的指针,为什么say.apply(this)会输出'undefined'?

谢谢。

在这种情况下,您的 this 确实不够精细,因为 color = 'red'; 具有以下等价物:global.color = 'red';。要使其与 this 相关联,您需要自己完成:this.color = 'red';

要从 o 对象中获取颜色值,您需要这样写:

say.apply(o);

这是使用 apply():

的好例子
function printArgs() {
  var join = [].join; // copy link of array.join into variable

  // call join with "this=arguments",
  // this call is equivalent with "arguments.join(':')"
  // here we have guarantee that method 'join()' was called from 'arguments'
  // (not from other object)
  var argStr = join.apply(arguments, [':']);

  console.log( argStr ); // output will looks like '1:2:3'
}

printArgs(1, 2, 3);

您还可以在这里找到有用的信息:

  • Meaning of "this" in node.js modules and functions
  • What is the difference between call and apply?
  • Javascript call() & apply() vs bind()?