【问题标题】:'this' is unequal to Bar in prototype'this' 不等于原型中的 Bar
【发布时间】:2012-09-03 19:50:36
【问题描述】:

在下面的代码 sn-p 中,'this.x()' 只能在情况 2 中调用(参见 main())。 同样 Bar 在情况 1 中不等于此值,但在情况 2 中等于。

function Class_Bar() {
    this.panel = null;
    this.init = function () {
        // do some stuff
        this.panel = 20;
    }
    this.apply = function () {
        alert(Bar == this);
        Bar.x();
        this.x();
    }
    this.x = function() {
        alert("Some friendly message");
        alert(Bar.panel);
    }
}

var Bar = new Class_Bar();

function Class_Factory() {
    this.factories = new Array();
    this.add = function (init, apply) {
        this.factories.push({"init":init, "apply":apply});
    }
    this.init = function () {
        for (var i = 0; i < this.factories.length; ++i) {
            this.factories[i]["init"]();
        }
    }
    this.apply = function () {
        for (var i = 0; i < this.factories.length; ++i) {
            this.factories[i]["apply"]();
        }
    }
}

var Factory = new Class_Factory();

function main() {
    // Case 1
    Factory.add(Bar.init, Bar.apply);

    Factory.init();
    Factory.apply();

    // Case 2
    Bar.init();
    Bar.apply();
}

main();

http://pastebin.com/fpjPNphx

任何想法如何“修复”/解决此行为?

我找到了一个可能的解决方案,但它似乎是一个“糟糕”的 hack。:Javascript: How to access object member from event callback function

【问题讨论】:

  • 如果我是你,我会考虑将对象本身传递给工厂,在你试图做的事情的背景下更有意义。

标签: javascript arrays object callback


【解决方案1】:

通过传递Bar.init,您实际上只是传递了函数而不是它属于Bar 的信息(即this 的值应该是什么)。您可以做的是绑定该信息:

Factory.add(Bar.init.bind(Bar), Bar.apply.bind(Bar));

【讨论】:

    猜你喜欢
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    相关资源
    最近更新 更多