Javascript";应用";函数似乎不适用于全局";这个"

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

本文关键字:quot 适用于 全局 不适用 这个 函数 应用 Javascript      更新时间:2023-09-26

我在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"的指针,为什么说.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);

你也可以在这里找到有用的信息:

  • ";这个";在node.js模块和函数中
  • 打电话和申请有什么区别
  • Javascript调用((&apply((和bind((