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

知识点:

Object.create的内部原理:

Object.create =  function (o) {

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

注意: prototype属性 是Javascript中函数的属性

原文地址:https://www.cnblogs.com/eret9616/p/10491514.html