在业余时间我尝试学习一点 JS,但我还是坚持主题中的主题。
var person = new Person("Bob", "Smith", 52);
var teacher = new Teacher("Adam", "Greff", 209);
function Humans(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
function Person(firstName, lastName, age) {
Humans.call(this, firstName, lastName);
this.age = age;
}
Person.prototype = Object.create(Humans.prototype);
Person.prototype.fullDetail = function() {
return this.firstName + " " + this.lastName + " " + this.age;
};
function Teacher(firstName, lastName, roomNumber) {
Humans.call(this, firstName, lastName);
this.room = roomNumber;
}
Teacher.prototype = Object.create(Humans.prototype);
Teacher.prototype.fullDetail = function() {
return this.firstName + " " + this.lastName + " " + this.room;
};
person.fullDetail();
谁能告诉我为什么我无法执行person.fullDetail();
?
如果您能对您的代码版本发表一些评论,我将非常感激,谢谢。
因为您是在定义对象的原型之前创建对象的。
当你这样做时
var person = new Person ("Bob", "Smith", 52);
你正在根据以下内容制作一个对象current的定义Person
。稍后在该代码中,您将更改原型Person
完整地
Person.prototype = Object.create(Humans.prototype);
要解决此问题,请创建您的对象after您已经完成了原型的重新分配。
function Humans(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
function Person(firstName, lastName, age) {
Humans.call(this, firstName, lastName);
this.age = age;
}
Person.prototype = Object.create(Humans.prototype);
Person.prototype.fullDetail = function() {
return this.firstName + " " + this.lastName + " " + this.age;
};
function Teacher(firstName, lastName, roomNumber) {
Humans.call(this, firstName, lastName);
this.room = roomNumber;
}
Teacher.prototype = Object.create(Humans.prototype);
Teacher.prototype.fullDetail = function() {
return this.firstName + " " + this.lastName + " " + this.room;
};
var person = new Person("Bob", "Smith", 52);
var teacher = new Teacher("Adam", "Greff", 209);
console.log(person.fullDetail());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)