1 回答

TA貢獻1816條經驗 獲得超4個贊
Physics.prototype = new Science();
//...
Physics.prototype = {
name: "Physics",
dificulty: "80%",
type: "Physical Science",
subFields: ["Electricity", "Mechanics", "Sound", "Optics", "Waves"],
};
第二行將覆蓋第一行。代碼完成后,原型就是新對象。與 不再有任何關系Science,因此沒有universal財產可以繼承。
您不需要替換prototype,而是需要添加:
Physics.prototype = new Science();
//...
Physics.prototype.name = "Physics";
Physics.prototype.dificulty = "80%";
Physics.prototype.subFields = "Physical Science";
Physics.prototype.name = ["Electricity", "Mechanics", "Sound", "Optics", "Waves"];
或者:
Physics.prototype = new Science();
//...
Object.assign(Physics.prototype, {
name: "Physics",
dificulty: "80%",
type: "Physical Science",
subFields: ["Electricity", "Mechanics", "Sound", "Optics", "Waves"],
});
Mathematics將需要類似的改變。
function log(elem) {
return console.log(elem);
}
//create supertype => Science
function Science() {}
//define Science prototype props
Science.prototype = {
constructor: Science,
dificulty: "Variable",
universal: true,
type: "science",
name: "science",
hasSubFields() {
return true;
},
};
//create 2 sub fields : Mathematics and Physics to inherit props from Science
function Mathematics(subField) {
this.subField = subField;
}
function Physics() {}
//let mathematics & Physics inherit science props
Mathematics.prototype = Object.create(Science.prototype);
Physics.prototype = Object.create(Science.prototype);
Physics.prototype.constructor = Physics;
//over write Mathematics inherited props and physics
Object.assign(Mathematics.prototype, {
constructor: Mathematics,
name: "Mathematics",
type: "Pure and applied Science",
});
Object.assign(Physics.prototype, {
name: "Physics",
dificulty: "80%",
type: "Physical Science",
subFields: ["Electricity", "Mechanics", "Sound", "Optics", "Waves"],
})
//make instance of Physics
let mechanics = new Physics();
mechanics.name = "mechanics";
mechanics.subFields = ["linear", "force", "force fileds"];
log(mechanics.universal);
添加回答
舉報