((如果重复重复,请关闭)
考虑到以下情况:
function Person(first, last) {
this.name = {
first,
last
};
};
Person.prototype.greeting = function() {
console.log('Hi! I\'m ' + this.name.first + '.');
};
function Teacher(first, last, subject) {
Person.call(this, first, last);
this.subject = subject;
}
//Teacher.prototype = Person.prototype;
//Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.constructor = Teacher;
const t = new Teacher('John','Smith','Math');
使用此功能有什么区别?
Teacher.prototype = Person.prototype;
or this
Teacher.prototype = Object.create(Person.prototype);
如果使用普通分配方法,则对Teacher.prototype
的更改也会影响Person.prototype
。这不是一个好主意,因为虽然老师是一个人,但一个人不一定是老师:
function Person(first, last) {
this.name = {
first,
last
};
};
Person.prototype.greeting = function() {
console.log('Hi! I\'m ' + this.name.first + '.');
};
function Teacher(first, last, subject) {
Person.call(this, first, last);
this.subject = subject;
}
// Bad:
Teacher.prototype = Person.prototype;
// Because:
Teacher.prototype.teachesClass = () => true;
// Person.prototype now has that too:
const p = new Person();
console.log(p.teachesClass());
现在,两个.prototype
相同,因此任何一个突变都会影响另一个。这几乎永远不是您想要的。
[相反,当您使用Object.create
方法时,对Teacher.prototype
的分配只会影响Teacher.prototype
。 Teacher.prototype
继承的对象Person.prototype
不会更改:
function Person(first, last) {
this.name = {
first,
last
};
};
Person.prototype.greeting = function() {
console.log('Hi! I\'m ' + this.name.first + '.');
};
function Teacher(first, last, subject) {
Person.call(this, first, last);
this.subject = subject;
}
// Good:
Teacher.prototype = Object.create(Person.prototype);
// Because:
Teacher.prototype.teachesClass = () => true;
// Person.prototype does not have teachesClass
const p = new Person();
console.log(p.teachesClass);