JavaScript原型链的继承过程

JavaScript原型链继承

1、定义父类型构造函数

function Father() {
    this.fatherName = 'father'
}

2、给父类型的原型添加方法

Father.prototype.getFatherName = function() {
    console.log(this.fatherName);
}

3、定义子类型的构造函数

function Son() {
    this.sonName = 'son'
}

4、父类型的对象赋值给子类型的原型

// 子类型的原型为父类型的实例对象
Son.prototype = new Father();

这一段代码是实现继承的关键。

5、将子类型原型的构造属性设置为子类型

Sub.prototype.contructor = Sub

6、给子类型原型添加方法

Son.prototype.getSonName = function() {
    console.log(this.sonName);
}

7、创建子类型实例对象,可以直接调用父类型的方法

var son = new Son();

son.getFatherName();  // father
发布了80 篇原创文章 · 获赞 135 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/qq_37954086/article/details/101679883