手记

js构造函数的继承

js构造函数的继承

js构造函数的继承

函数function 方法的继承是常见的,那么下面我说的就是函数function之间的继承

构造函数

function parent() {}
parent.prototype.name = 'dili';
parent.prototype.age =40;

function child() {}
child.prototype.age = 23 

// 以上是两个构造函数
new实例化
function parent() {}
parent.prototype.name = 'dili';
parent.prototype.age =40;

//new构造函数 创建实例化对象
const fn = new parent(); 
console.log(fn.name, fn.age) // 'dili',40

以上明显看出fn函数继承了parent函数的属性,此处是最常见的实例化对象。

此处可以思考 fn.__proto__和parent.prototype的指向
函数之间的继承
function parent(x) {
    this.x = x;
}
parent.prototype.name = 'dili';
parent.prototype.age =40;

function child(x) {
    parent.call(this, x); //继承属性
}
child.prototype.age = 23 

// child原型对象指向parent的实例化对象
child.prototype = Object.create(parent.prototype);
// child原型构造函数指向child
child.prototype.constructor = child;

const fn = new child('x');
console.log(fn.name, fn.age) // 'dili',23

使用以上方法可以实现多层函数的继承,但并不影响构造函数的指向。

fn.__proto__ === child.prototype;

//child.__proto__ === Function.prototype
child.prototype.__proto__ === parent.prototype

//parent.__proto__ === Function.prototype
parent.prototype.__proto__ == Object.prototype

//Function.__proto__ === Function.prototype
//Function.prototype.__protope === Object.prototype
1人推荐
随时随地看视频
慕课网APP