function Parent () {
this.name = 'huang';
}
Parent.prototype.getName = function () {
console.log(this.name);
}
function Child () {
}
Child.prototype = new Parent();
var child1 = new Child();
console.log(child1.getName()) // huang
问题:引用类型的属性被所有实例共享,举个例子:
function Parent () {
this.names = ['huang', 'huang'];
}
function Child () {
}
Child.prototype = new Parent();
var child1 = new Child();
child1.names.push('test');
console.log(child1.names); // ["huang", "huang", "test"]
var child2 = new Child();
console.log(child2.names); // ["huang", "huang", "test"]
function Parent () {
this.names = ['xianzao', 'zaoxian'];
}
function Child () {
Parent.call(this);
}
var child1 = new Child();
child1.names.push('test');
console.log(child1.names); // ["xianzao", "zaoxian", "test"]
var child2 = new Child();
console.log(child2.names); // ["xianzao", "zaoxian"]
优点:
function Parent (name) {
this.name = name;
}
function Child (name) {
Parent.call(this, name);
}
var child1 = new Child('xianzao');
console.log(child1.name); // xianzao
var child2 = new Child('zaoxian');
console.log(child2.name); // zaoxian
缺点: 方法都在构造函数中定义,每次创建实例都会创建一遍方法。
function Parent (name) {
this.name = name;
this.colors = ['red', 'blue', 'green'];
}
Parent.prototype.getName = function () {
console.log(this.name)
}
function Child (name, age) {
Parent.call(this, name); // 构造器借用了
this.age = age;
}
Child.prototype = new Parent(); // 原型链继承
Child.prototype.constructor = Child; // 将构造器引用指回来
var child1 = new Child('kevin', '18');
child1.colors.push('black');
console.log(child1.name); // kevin
console.log(child1.age); // 18
console.log(child1.colors); // ["red", "blue", "green", "black"]
var child2 = new Child('daisy', '20');
console.log(child2.name); // daisy
console.log(child2.age); // 20
console.log(child2.colors); // ["red", "blue", "green"]
优点:融合原型链继承和构造函数的优点,是 JavaScript 中最常用的继承模式。
function createObj(o) {
function F(){}
F.prototype = o;
return new F();
}
缺点: 包含引用类型的属性值始终都会共享相应的值,这点跟原型链继承一样。
var person = {
name: 'kevin',
friends: ['daisy', 'kelly']
}
var person1 = createObj(person);
var person2 = createObj(person);
person1.name = 'person1';
console.log(person2.name); // kevin
person1.friends.push('taylor');
console.log(person2.friends); // ["daisy", "kelly", "taylor"]
创建一个仅用于封装继承过程的函数,该函数在内部以某种形式来做增强对象,最后返回对象。
function createObj (o) {
var clone = Object.create(o);
clone.sayName = function () {
console.log('hi');
}
return clone;
}