Object.create vs .prototype

问题描述 投票:0回答:1

((如果重复重复,请关闭)

考虑到以下情况:

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);
javascript prototype prototypal-inheritance oojs
1个回答
0
投票

如果使用普通分配方法,则对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.prototypeTeacher.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);
© www.soinside.com 2019 - 2024. All rights reserved.