簡體   English   中英

JavaScript 打印兩次

[英]JavaScript Printing Twice

 function Person() { throw new Error("The person is abstract constructor function"); } Person.prototype.personName = "John"; Person.prototype.age = 21; Person.prototype.getDetails = function() { return `Person name ${this.personName} and age is ${this.age}.`; }; function Teacher() {} Teacher.prototype = Object.create(Person.prototype); Teacher.prototype.mainSubject = "Physics"; Teacher.prototype.getDetails = function() { return `${this.__proto__.getDetails()} main subject is ${this.mainSubject} `; }; var teacher1 = new Teacher(); console.log(teacher1.getDetails());

它打印“人名 John,年齡 21。主要科目是物理,主要科目是物理”。 這行主科是Physics不應該來兩次。

人名約翰,年齡 21 歲。主修科目是物理。

您正在覆蓋 Person with Teacher 的 getDetails

 function Person() { throw new Error("The person is abstract constructor function"); } Person.prototype.personName = "John"; Person.prototype.age = 21; Person.prototype.getDetails = function() { return `Person name ${this.personName} and age is ${this.age}.`; }; function Teacher() {} Teacher.prototype.person = Object.create(Person.prototype); // Here changed Teacher.prototype.mainSubject = "Physics"; Teacher.prototype.getDetails = function() { return `${this.person.getDetails()} main subject is ${this.mainSubject} `; // Here changed }; var teacher1 = new Teacher(); console.log(teacher1.getDetails());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM