简体   繁体   English

Object.create 与 .prototype

[英]Object.create vs .prototype

(Please close IF duplicate) (如有重复请关闭)

Given the following scenario:鉴于以下场景:

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');

What would be the difference of using this?使用这个会有什么区别?

 Teacher.prototype = Person.prototype;


   or this


  Teacher.prototype = Object.create(Person.prototype);

If you use the plain assignment method, changes to Teacher.prototype will also affect Person.prototype .如果您使用普通分配方法,对Teacher.prototype更改也会影响Person.prototype This is not a good idea, because while a Teacher is a Person, a Person is not necessarily a Teacher:这不是一个好主意,因为虽然老师是人,但人不一定是老师:

 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());

Now, both .prototype s are the same, so any mutations to one will affect the other.现在,两个.prototype是相同的,因此对一个的任何突变都会影响另一个。 This is pretty much never what you want.这几乎永远不是你想要的。

In contrast, when you use the Object.create method, assignments to Teacher.prototype will only affect Teacher.prototype .相反,当您使用Object.create方法时,对Teacher.prototype赋值只会影响Teacher.prototype The object that Teacher.prototype inherits from, Person.prototype , will not be changed:该对象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);

Looking at the prototype chain:查看原型链:

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