[英]How call an object property from a click event inside a method of the same object
[英]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.