[英]Object.create vs .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;
}
//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);
查看原型鏈:
Teacher.prototype = Person.prototype;
// You get:
Teacher.prototype <- Object.prototype
Person.prototype <- Object.prototype
Teacher.prototype === Person.prototype // (same object)
// Compare to
Teacher.prototype = Object.create(Person.prototype);
// You get:
Teacher.prototype <- Person.prototype <- Object.prototype
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.