2012-11-07 49 views
0

可能重複:
Crockford’s Prototypal inheritance - Issues with nested objectsJavascript繼承 - 從另一個原型調用函數

我在得到以下代碼從原型原型B到執行功能相關的問題,並想知道是否有任何簡單的解決方案:

var Ob = function() { 
    test = 'hi'; 
} 

Ob.prototype.A = { 
    that : this, 
    root : this, 
    goB : function() { 
    var that = this; 

    console.log('hello'); 
    that.B.wtf(); 
    } 
} 

Ob.prototype.B = { 
    that : this, 
    root : this, 
    wtf : function() { 
    var that = this; 

    console.log(that); 
    } 
} 

test = new Ob; 
test.A.goB(); 
+0

'那= this'不引用你的'Ob'實例,只是你把在'Ob.prototype'屬性的對象! – Bergi

+0

相關:[與嵌套對象繼承的問題](http://stackoverflow.com/questions/10131052/crockfords-prototypal-inheritance-issues-with-nested-objects) – Bergi

回答

1

你需要線了你的屬性的對象被創建後:

var Ob = function() { 
    var that = this; 

    // set the current root to this instance and return the object 
    this.getA = function() { 
     that.A.currentRoot = that; 
     return that.A; 
    }; 

    this.getB = function() { 
     that.B.currentRoot = that; 
     return that.B; 
    }; 
}; 

Ob.prototype.A = { 
    goB : function() { 
     var that = this.currentRoot; 

     console.log('hello'); 
     that.getB().wtf(); 
    } 
}; 

Ob.prototype.B = { 
    wtf : function() { 
     var that = this.currentRoot; 

     console.log(that, this); 
    } 
}; 


test = new Ob; 
test.getA().goB(); 

一個相當骯髒的黑客是使用特權方法父對象充實到子對象,並返回它讓你有通過屬性訪問父對象。骯髒的部分是,如果你緩存對象的屬性不保證有正確的值。所以這或多或少是一種做法,儘管你不應該這樣做。

+0

'A.root = B.root = this;'構造函數中沒有'A'或'B'變量。如果你的意思是'this.A.root = this.B.root = this;',那麼每次調用構造函數時都會覆蓋該值。 –

+0

好點。在我重新格式化答案之前,我應該再次檢查。我會更新答案。 –

+0

正是我所期待的。謝謝Torsten。 –

2

當你分配對象文字ABOb原型,你把兩個對象常量與原型的一些方法。你沒有把這些方法放在原型上。因此,當您在實例testthis的上下文中對這些對象文字執行該方法時,並不意味着您認爲它的含義。

+1

構造函數被調用。沒有錯誤。 –

+0

oh thanx ....... – hvgotcodes