首页 > 解决方案 > Object.create 与 .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);

标签: javascriptprototypeprototypal-inheritanceoojs

解决方案


如果你使用普通的赋值方法,对 的更改Teacher.prototype也会影响Person.prototype. 这不是一个好主意,因为虽然 Teacher 是 Person,但 Person 不一定是 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());

现在,两个.prototypes 是相同的,因此对一个的任何突变都会影响另一个。这几乎不是你想要的。

相反,当您使用该Object.create方法时,分配 toTeacher.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

推荐阅读