继承
这是一篇关于js继承的文章,具体主要的js高程上面都有,这里只是简单理一理,外加一些自己的看法。
下面直接上干货
1 原型链继承
- 基础依赖:可以查看我以前写的文章原型对象和原型链
- 实例
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log('your name:' + this.name);
}
function Child(name) {
this.name = name;
}
Child.prototype = new Parent('Nickle');
Child.prototype.constructor = Child;
var child = new Child('Jack');
child.sayName();
打印结果为 your name Jack
- 缺点
- 当超类中存在引用类型时,该属性会被所有的实例共享
- 在创建子类的过程中无法向父类传递数据,让子类使用父类的构造器,而是只能通过new Parent(‘Nickle’) 去解决
在别的地方相似的文章下面看到一个问题:子类的 __proto__ 属性为什么指向父类。而不是指向Function.prototype,这里子类是Child,父类为Parent。
我想他可能吧概念搞混淆了,所有的引用类型的__proto__指向的是构造函数的prototype,即方法Child和Parent的__proto__指向的都是Function.prototype。在本例中实例child的__proto__指向的是构造函数Child的prototype,而我们已经做了这步操作:Child.prototype = new Parent(‘Nickle’);使得Child.prototype成为了parent的实例。下面给出测试
// 为了测试我将继承写为
var parent = new Parent('Nickle');
Child.prototype = parent;
Child.__proto__ === Parent.__proto__; // true
Child.__proto__ === Function.prototype; // true
child.__proto__ === parent; // true
child.__proto__.__proto__ === Parent.prototype; // true
2 借用构造函数
- 基础依赖:即在子类的构造函数中调用超类型构造函数,可以通过call 和 apply来进行。
- 实例
function Parent(name) {
this.colors = ['white', 'black', 'green'];
this.name = name
}
function Child(name) {
// 完成了继承,同时还实现了传递参数
Parent.call(this, 'Nickle');
}
var child1 = new Child();
child1.colors.push('red');
console.log(child1.colors); // ["white", "black", "green", "red"]
var child2 = new Child();
console.log(child2.colors); // ["white", "black", "green"]
- 缺点:函数无法复用。
3 组合式继承:使用原型和借用构造函数
实例
function Parent(name) { this.name = name; this.colors = ['white', 'black', 'green']; } Parent.prototype.sayName = function() { console.log(this.name); } function Child(age, name) { Parent.call(this); this.age = age; } Child.prototype = new Parent(); Child.prototype.constructor = Child; Child.prototype.sayAge = function() { console.log(this.age); } var child1 = new Child('Nickle', 20); child1.colors.push('red'); // ["white", "black", "green", "red"] child1.sayName(); // Nickle child1.sayAge(); // 20
var child2 = new Child('Grey', 27);
console.log(child2.colors); // ["white", "black", "green"]
child2.sayName(); // Grey
child2.sayAge(); // 27