创建子对象类时,将方法包括在prototype属性中的原因是什么?

时间:2019-02-21 21:50:16

标签: javascript oop inheritance prototype

在OOJS中创建“子”对象类时,我看到两种不同的执行方式。

首先

function Person(name) {
  this.name = name;
  this.sayHi = function(){
    alert("Hi");
  }
}

function Teacher(name) {
  Person.call(call, name);
  }
}

var teacher1 = new Teacher("Tom");

第二,

function Person(name) {
  this.name = name;
}

Person.prototype.sayHi = function() {
  alert("Hi");
}

function Teacher(name) {
   //same as the first example
}

Teacher.prototype = Object.create(Person.prototype);
Object.defineProperty(Teacher.prototype, 'constructor', { 
  value: Teacher, 
  enumerable: false, // so that it does not appear in 'for in' loop
  writable: true 
});

第二种方法似乎不必要地复杂。我仍然可以通过两种方法访问Teacher.prototype。第二种方法背后的原因是什么?

0 个答案:

没有答案
相关问题