繁体   English   中英

Javascript。 如何在同一类的对象属性内调用方法?

[英]Javascript. How to call a method inside an object property of the same class?

这看起来可能令人困惑(或没有),但是这一直困扰着我。 因此,我有一个类型为对象hospot的类属性,该属性基本上已声明为:

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

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

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

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

顺便说一下,我试着用以下方法替换this.blah()

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

但是有一个新问题。 它说该方法中的某些变量未定义。 现在该方法具有该类绝对具有并定义的变量this.x ,只是出于某种原因而没有使用它。

帮帮忙。 :) 谢谢

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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM