2012-04-05 113 views
0

我該如何做這個例子的繼承。在這種情況下如何做原型繼承?

我試圖創建一個對象字面值作爲一個單例。在這個我想提取我的課程。接下來,這些類應該在適用時相互繼承

像這樣:

var Singleton = { 

    car: function() { 
     this.engine= true; 
    }, 

    ford: function() { 
     this.color = 'red'; 
    } 
}; 

我願意讓福特從酒吧繼承,但我不能這樣做

ford: function() { 
     this.color = 'red'; 
     this.prototype = new this.car(); 
    } 

任何想法?

+1

底漆要開始,使用構造函數,而不是對象文本的。 – 2012-04-05 19:28:10

+0

[JavaScript繼承模式](http://bolinfest.com/javascript/inheritance.php)。 – 2012-04-05 19:28:39

+0

「bar繼承foo」究竟意味着什麼? foo和bar是否會被用作帶new'調用的構造函數? – Phrogz 2012-04-05 19:35:25

回答

2
var Something = { 

    foo: function() { 
     this.greet = 'hello'; 
    }, 
    bar: function() { 
     this.color = 'blue'; 
    } 
}; 

Something.bar.prototype = new Something.foo(); 
alert((new Something.bar()).greet) 

這裏是inheritance

+0

這正是我想要的。十分感謝! – Kriem 2012-04-06 07:13:46

1

如果你想使foobar繼承屬性,那麼你可以做這樣的事情(注意,那這樣,你不會有原型性質,儘管inhereted):

var Something = { 
    foo: function() { 
     this.greet = 'hello'; 
    }, 
    bar: function() { 
     Something.foo.call(this); 
     this.color = 'blue'; 
    } 
}; 

,然後用它像這樣:

var bar = new Something.bar(); 
bar.color // blue 
bar.greet // hello 
0

你可以做這樣的事情:

function Foo() { 
    this.greet = "hi!"; 
} 

Bar.prototype = new Foo; 

function Bar(color) { 
    Foo.apply(this.arguments); 
    this.color = color; 
} 

var myBar = new Bar("red"); 

A Bar創建此方式將同時具有greetcolor屬性。此方法保留了原型屬性。

+0

將'Foo.apply(this.arguments);'改爲'Foo.apply(this,arguments);'。另外,創建原型對象的一個​​更好的方法是'Bar.prototype = Object.create(Foo.prototype);'。儘管這個簡單的例子不是非常重要。 – 2012-04-05 20:22:07