0

这可能看起来令人困惑(或没有),但它一直让我难以置信。所以我有一个 object hospot类型的类属性,它基本上是声明的:

Cannon.prototype.hotspot = {stuff: this.blah(...) };

现在bla()方法实际上也是“类”的原型。

Cannon.prototype.blah = function() { ... };

现在我有一个问题,它说方法 blah() 不存在,我假设这是因为“ this”与对象热点的上下文有关,而不是Cannon的“类”。现在我想知道如何调用方法 blah()

顺便说一句,我试过用这个替换this.blah()

Cannon.prototype.blah.call(this, ...);

但是有一个新问题。它表示方法中的某些变量未定义。现在该方法具有this.x之类的变量,该类绝对具有并已定义,只是由于某种原因没有拾取它。

帮助伙计们。:) 谢谢

4

1 回答 1

0

Thera 有两个对象:Cannon 和 Hotspot。因为“Cannon.prototype.hotspot”上的“{..}”是一个对象创建字面量。

您需要将它们分开:

function Cannon(hotspot) {
    if ( hotspot.constructor == Hotspot ) {
        this.hotspot = hotspot;
        // this.hotspot = new Hotspot();
        this.hotspot.setCannon(this);
    } else {
        throw "type mismatch: hotspot"
    }
}
// Less Flexible Constructor
// No need to pass "Hotspot" object
// function Cannon() {
//     this.hotspot = new Hotspot();
//     this.hotspot.setCannon(this);
// }

Cannon.prototype.blah = function(a){
    alert("Hello "+a);
};

function Hotspot() {
    this.cannon = null;
}
Hotspot.prototype.setCannon = function(cannon){
    if ( cannon.constructor == Cannon ) {
        this.cannon = cannon;
    } else {
        throw "type mismatch: cannon"
    }
};
Hotspot.prototype.stuff = function(a){
    if ( this.cannon ) {
        this.cannon.blah(a);
    }
};

您可以对此进行测试:

var hotspot = new Hotspot();
var aCannon = new Cannon(hotspot);
aCannon.hotspot.stuff("World");

或者

var aCannon = new Cannon( new Hotspot() );
aCannon.hotspot.stuff("World");
于 2013-10-31T07:26:11.327 回答