2014-01-30 111 views
1

如果我們有像父對象:Javascript繼承的對象

var Animal = function(name) { 
    this.name = name; 
    return this; 
} 

,我們使用prototype像:

Animal.prototype.Dog = function(){ 
    console.log(this.name); 
} 

這只是偉大工程。 但是我想實現的是繼承子對象的parent屬性一樣

Animal.prototype.Child = { 
    Dog : function(){ 
     console.log(this.name); 
    } 
} 

我們怎樣才能做到這一點。我試圖找兩天。我也試過:

Animal.prototype.Child = { 
    that:this, 
    Dog : function(){ 
     console.log(this.that.name); 
    } 
} 

但這裏that包含window對象不是Animal。此外

Animal.prototype.Child = { 
    Animal: new Animal('Puppy'), 
    Dog : function(){ 
     console.log(this.Animal.name); 
    } 
} 

一種選擇這裏。

+1

我真的不明白你在用'Animal.prototype.Child = {Dog:....}來達到什麼目的。這不是繼承通常的樣子。看看http://stackoverflow.com/q/17392857/218196。 –

回答

2

您的繼承鏈看起來不正確。你會創建兩個不同的構造函數。每個構造函數創建一個對象。繼承部分設置原型鏈並在子類中調用「超級」。換句話說,你可以這樣做:

// Constructor for animals 
function Animal(name) { 
    this.name = name; 
    // no need to return this 
    // as a constructor returns the instance 
    // when using the `new` keyword 
} 

// Public methods of all animals 
Animal.prototype.say = function(){ 
    // implement 
}; 

// Constructor for dogs 
function Dog(name) { 
    // Call "super", inherit parent properties 
    Animal.apply(this, arguments); 
} 

// Public methods of dogs 
Dog.prototype.fetch = function(){ 
    // implement 
}; 

// Setup prototype inheritance chain 
// and save a reference to our constructor 
Dog.prototype = Object.create(Animal.prototype); 
Dog.prototype.constructor = Dog; 

即使你的產業並沒有看的權利,這是一個普遍的誤解:

Animal.prototype.Child = { 
    that: this, //<--- 
    ... 
} 

this是一個功能的情況下,和值取決於該函數如何被調用。 this在上面的代碼是window;注意到沒有功能。

在下面的代碼,thisobj

var obj = { 
    prop: 'foo', 
    method: function() { 
    return this.prop; 
    } 
}; 

obj.method(); 
//^ logs "foo" because we are using dot notation (`obj` is the receiver) 

如果我們不叫點符號將無法正常工作的功能。再次,this只取決於如何調用函數。這是行不通的:

var fn = obj.method; 
fn(); // won't work 
fn.call(obj); //=> will work, we pass the context explicitly