簡體   English   中英

Object.create 與 .prototype

[英]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.

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