我是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 ?
的'constructor'屬性是幾乎沒用。它沒有實際用途,可以被腳本覆蓋,因此不可靠。 – 2012-07-13 23:48:44
你可能想看看這個:http://pivotallabs.com/users/pjaros/blog/articles/1368-javascript-constructors-prototypes-and-the-new-keyword – 2012-07-13 23:50:35
@JamesBlack謝謝,我會帶一個看它。 – 2012-07-13 23:59:22