2012-07-13 47 views
3

我是Javascript的初學者,並且很難理解構造函數和原型屬性之間的關係。在JavaScript中無法真正理解構造函數和原型關係

我知道Prototype對象具有指向構造函數的constructor屬性。構造函數有一個指向原型對象的prototype屬性。

這裏有一個代碼,我試圖用(我的問題是在代碼註釋)瞭解:

function Car(){}; 
var myCar = new Car(); 
console.log(Object.getPrototypeOf(myCar)); //why this prints "Car" Object ? isn't it the constructor not the prototype object ? why the prototype object is not printed ? 


var Vehicle = { 
    getName : function(){ 
     return "hello"; 
    } 
}; 
Car.prototype = Vehicle ; //I'm trying to change the prototype property in the constructor to "Vehicle" Object is that done right ? 
console.log(Object.getPrototypeOf(myCar).getName()); //Why am i getting getName() function does not exist ? 
+1

的'constructor'屬性是幾乎沒用。它沒有實際用途,可以被腳本覆蓋,因此不可靠。 – 2012-07-13 23:48:44

+1

你可能想看看這個:http://pivotallabs.com/users/pjaros/blog/articles/1368-javascript-constructors-prototypes-and-the-new-keyword – 2012-07-13 23:50:35

+0

@JamesBlack謝謝,我會帶一個看它。 – 2012-07-13 23:59:22

回答

6

爲什麼這個版畫「汽車」的對象?是不是構造函數不是原型對象?爲什麼原型對象沒有打印?

這就是Chrome(或您使用的瀏覽器)如何命名對象。如果你在性仔細看,果然是Car.prototype

enter image description here

我試圖改變原型屬性在構造函數中「車輛」對象是做對嗎?

您無法更改現有對象的原型,只能對其進行擴展。設置Car.prototype = Vehicle;只會更改原型Car未來情況下,現有的仍然指向原來的原型對象,它不具有getName屬性:

// create a new instance after setting the new prototype 
var myCar2 = new Car(); 
// yields false 
console.log(Object.getPrototypeOf(myCar) === Object.getPrototypeOf(myCar2)); 

這確實不是與原型有什麼關係,但是JavaScript中的賦值和引用是如何工作的。想象一下,我有以下對象:

var foo = { 
    bar: { 
     answer: 42 
    } 
}; 

,並假定我給你foo.bar到其他對象的屬性:

var baz = {}; 
baz.xyz = foo.bar; 

設置foo.bar爲其他值現在,像foo.bar = {},不會改變值爲baz.xyz,它仍然會引用前一個對象。

只有延伸原始對象(延伸的原型),或改變其屬性將產生作用,因爲這兩種,foo.barbaz.xyz指代相同的對象:

foo.bar.answer = 21; 
console.log(baz.xyz.answer); // shows 21 
// console.log(foo.bar === baz.xyz); // yields true 
+0

很好的答案,非常完整。 – elclanrs 2012-07-14 00:04:21