javascript - "this"对象的奇怪值

标签 javascript function this ecmascript-5

关于这段代码:

var name = "Jaguar";
var car = {
  name:"Ferrari",
  getName:function(){
    return this.name;
  }
};

alert((car.getName = car.getName)());

输出是:Jaguar

为什么this对象对应的是Window,而不是car变量中包含的对象?

似乎将对象的函数重新分配给自身的事实导致在调用函数时丢失对对象的 this 分配...

我试图猜测:它是否存在一种机制(使用变量或其他)来关注对象函数的非重新分配,以便如果发生这种情况,这种机制将阻止分配this 关键字像往常一样(等于对象)?

最佳答案

原因相当微妙:JavaScript 中的this 完全由函数的调用方式 决定。要在调用 getName 期间将 this 设置为 car,您必须在从中检索它时立即调用 getName car 对象,像这样:

car.getName() // or
car["getName"]()

(或者通过 Function#callFunction#apply ,它允许您明确指定 this 的值。)

您在示例中所做的实际上是这样的:

// Set f to the result of the assignment expression,
// which is a reference to the getName function
var f = (car.getName = car.getName);

// Call it (separately)
f();

...这是不同的。以这种方式调用的函数将 this 设置为全局对象(window,在浏览器中)。 (严格模式除外;在严格模式下 this 将是 undefined。)

更多(来 self 贫血的博客):

Does it exist a kind of mechanism (using variable or other) that keep an eye on the non-reassignement of an object's function so that if that situation happens, this mechanism would prevent the assignement of the this keyword as usual (as being equals to the object)?

我不完全确定我是否遵循了这个问题,但是如果您想要一个始终具有预设 this 值的函数,那么是的,有几种方法可以做到这一点。

一种是使用新的ES5函数bind :

var name = "Jaguar";
var car = {
  name: "Ferrari"
};
car.getName = function(){
  return this.name;
}.bind(car);
alert((car.getName = car.getName)()); // "Ferrari"

bind 返回一个函数,该函数始终将 this 设置为您提供的参数。

另一种方法是使用闭包。事实上,您可以非常轻松地在 ES3 中创建类似 bind 的函数:

function pseudoBind(func, thisArg) {
    return function() {
        return func.apply(thisArg, arguments);
    };
}

这并没有完成 bind 所做的所有事情,但它完成了 this 部分。然后你会:

var name = "Jaguar";
var car = {
  name: "Ferrari"
};
car.getName = pseudoBind(function(){
  return this.name;
}, car);
alert((car.getName = car.getName)()); // "Ferrari"

关于闭包的更多信息(再次来自博客):

在未来的规范中,我们将获得一种声明​​性的方式来创建具有预设 this 值的函数(所谓的“arrow functions”,因为它们的语法涉及使用 => 而不是 function 关键字)。

关于javascript - "this"对象的奇怪值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13143587/

相关文章:

javascript - 过滤数组困惑

c++ - 在 C++ 程序中使用多个 .cpp 文件?

javascript - jQuery:在 $.ajax 成功函数中使用 $(this)

JavaScript/JQuery : use $(this) in a variable-name

javascript - 如何跨多个组件共享通用功能

javascript - 正则表达式形式 {m,n} 不使用上限

javascript - jQuery - 删除一个区分大小写的单词

javascript:传回对象时出错

python-3.x - 使用Python银行系统以相同的名称查找多个帐户

javascript - 该函数可以工作,但报告 this.refresh() 不是一个函数