證明的差異最簡單的方法是通過從你的榜樣的線路之一,看着我們所擁有的
function add() {
this.name = 'suresh';
this.lastname = 'kumar';
}
var b = new add();
// b.city = 'coimbatore'; // this line removed
add.city = 'coimbatore';
現在,什麼是b.city
?
b.city; // undefined
沒有未來的實例都會有一個城市的性質要麼,所以它不是設置的只是順序導致b
沒有擁有它。
var c = new add();
c.city; // undefined
這意味着設置在構造一個屬性上有構造的對象沒有影響(有一些特殊的例外,如原型屬性)
發生這種情況,因爲add
構造函數是它自己的對象和new add
創建的對象是實例add
,所以繼承自add.prototype
而不是add
本身。
如果你想每個實例繼承的東西,如果他們不自己的屬性它的好,那麼你可以將它們添加到構造函數的原型。要小心,如果你添加對象雖然任何更改將修改爲所有實例。
考慮
add.prototype.city = 'coimbatore';
b.city; // "coimbatore"
// and don't have to worry if you change it on an instance
b.city = 'fizz';
c.city; // "coimbatore"
而且危險我警告與對象
add.prototype.foo = {bar: 'baz'};
b.foo.bar; // "baz"
// but have to worry if you change it on an instance
b.foo.bar = 'fizz';
c.foo.bar; // "fizz", it got changed too :(
你問'add.city' VS'加()。現在city'? – Bergi
好吧,'add!== b'。一個是函數,另一個是對象實例。 – Bergi