Javascript继承(原始写法,非es6 class)

知识点:

Object.create的内部原理:

Object.create =  function (o) {

     var  F =  function  () {};
     F.prototype = o;
     return  new  F();
};
 
就是创建一个对象 然后把这个对象的__proto__原型对象指向o了 参数o是一个原型对象
 
 
 
下面讲一下Javascript中的继承:
 
function Person(name){
  this. name = name
}
 
// 在Person的原型对象上添加方法 
Person.prototype.greet = function(){ console.log(` hello ${this.name}` }
 
function Teacher(name){
  Person.call(this,name)
}
 
/* 到此,Teacher和Person的原型对象上 都指向Object,   constructor分别指向自身函数
 
// 将Teacher的原型对象设置
Teacher.prototype = Object.create(Person.prototype)
 
/* 到此 Teacher的原型对象上没有constructor属性 如果调用实例化出来的teacher1的原型对象,就是在沿着原型链调用Person原型对象上的constructor
 
Teacher.prototype.constuctor  = Teacher
 
到此继承完毕

猜你喜欢

转载自www.cnblogs.com/eret9616/p/10491514.html
今日推荐