我在MDN上閱讀了newjavascript 中的關鍵字并遇到了這一行:
當使用 new 呼叫函式時,建構式的原型屬性將成為結果物件的原型。
但是,下面的代碼并沒有像我預期的那樣運行。我假設這Car.prototype會回傳 Car 的原型物件。但它似乎只回傳一個空物件。我在這里想念什么?
function Car(make, model, year) {
this.make = make,
this.model = model,
this.year = year,
this.started = false,
this.start = function () {
this.started = true;
}),
this.stop = function () {
this.started = false;
});
}
let corolla = new Car("Toyota", "Corolla", 2016);
console.log(Object.getPrototypeOf(corolla)); //{}
console.log(Car.prototype); //{}
uj5u.com熱心網友回復:
你是絕對正確的。但是,原型是一個空物件,因為您從未為其分配任何屬性。(相反,您將屬性分配給新創建的物件本身。)
而不是在建構式體內部進行分配this.start,this.stop您必須在建構式內部Car.prototype.start和Car.prototype.stop外部進行分配(如下)。
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.started = false;
}
Car.prototype.start = function () {
this.started = true;
};
Car.prototype.stop = function () {
this.started = false;
};
let corolla = new Car("Toyota", "Corolla", 2016);
console.log(Object.getPrototypeOf(corolla));
console.log(Car.prototype);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/529495.html
