欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript原型继承

程序员文章站 2022-06-15 15:03:02
...

JavaScript原型继承

function A() {
    this.a = 'A'
}

A.prototype.showA = function () {
    console.log(this.a)
};

function B() {
    A.call(this);
    this.b = 'B'
}

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;    // 把B原型的构造函数修复为B
B.prototype.showB = function () {
    console.log(this.b)
};

b = new B();
b.showA();
b.showB();
console.log('b instanceof B: ', b instanceof B);
console.log('b instanceof A: ', b instanceof A);


打印结果:

A
B
b instanceof B:  true
b instanceof A:  true

封装可复用继承函数:

function inherit(parent, child) {
    child.prototype = Object.create(parent.prototype);
    child.prototype.constructor = child;
}

实现继承:

function A(a) {
    this.a = a
}

A.prototype.showA = function () {
    console.log(this.a)
};

function B(a, b) {
    A.call(this, a);
    this.b = b
}

inherit(A, B);  // 继承

B.prototype.showB = function () {
    console.log(this.b)
};

b = new B('aaa', 'bbb');
console.log(b.a);
console.log(b.b);
b.showA();
b.showB();
console.log('b instanceof B: ', b instanceof B);
console.log('b instanceof A: ', b instanceof A);

打印结果:

aaa
bbb
aaa
bbb
b instanceof B:  true
b instanceof A:  true

学习参考:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
https://www.liaoxuefeng.com/wiki/1022910821149312/1023021997355072