【问题标题】:"this" lost in javascript while referencing another object's function [duplicate]“this”在引用另一个对象的函数时在javascript中丢失[重复]
【发布时间】:2012-06-27 01:55:59
【问题描述】:

可能重复:
JavaScript losing “this” object reference with private/public properties

为什么第二个警报显示的是窗口对象,而不是 O(甚至是 P)对象?

window.name = "test window";

O = {
    name : 'object O',
    f : function() {
        alert(this.name); // 2nd alert
    }
}

P = {
    name : 'object P',
    f : function() {
        alert(this); // 1st alert
        var of = O.f;
        of();
    }
}

P.f();

换句话说,对对象函数的直接调用怎么能在窗口的上下文中呢?我想这是一个关闭的问题,但我不知道切换发生在哪里。

谢谢。

【问题讨论】:

  • 因为您已将O.fO 分离。

标签: javascript window this


【解决方案1】:

当你这样做时:

var of = O.f;
of();

你的this 在这里被破坏了,因为this 并没有真正被锁定在 JavaScript 中。它具有很强的延展性,在你的情况下,你可以做一些事情来让它更好地工作。

您可以执行以下任何操作来正确绑定它:

var of = O.f.bind(this);
of();

var of = O.f
of.call(this);

或者只是

O.f.call(this);

【讨论】:

  • 您好,感谢您的回答。确实有将函数绑定到 this 的解决方案,我已经在实际代码中使用了它,但我的问题更多的是“这里发生了什么?为什么这会变成这一行的窗口?”
【解决方案2】:

如果你想保持O 的范围,那么试试这个

window.name = "test window";

O = {
    name : 'object O',
    f : function() {
        alert(this.name); // 2nd alert
    }
}

P = {
    name : 'object P',
    f : function() {
        alert(this.name); // 1st alert
        var of = O.f;
        of(); // loses scope since this.of does not exist it calls using anonymous window scope
        of.call(O); // passes O as scope
        of.call(P); // passes P as scope

        this.of = O.f;
        this.of(); // maintains current P scope


    }
}

P.f();​

这是一个小提琴:http://jsfiddle.net/QVSDA/

【讨论】:

  • 啊,好吧!对,所以答案是“它被称为匿名函数。不过,我发现对象内部的函数调用可以被视为匿名函数真的很奇怪......
猜你喜欢
  • 1970-01-01
  • 2015-05-10
  • 2011-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
相关资源
最近更新 更多