function extend(child, parent) {
var F = function(){}; //定义一个空的构造函数
F.prototype = parent.prototype; //设置为父类的原型
child.prototype = new F(); //子类的原型设置为F的实例,形成原型链
child.prototype.constructor = child; //重新指定子类构造函数指针
}
function Parent(name) {
this.name = name;
this.colors = ['red', 'yellow'];
}
Parent.prototype.sayName = function() {
alert(this.name);
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
extend(Child, Parent); //实现继承
Child.prototype.sayAge = function() {
alert(this.age);
}
var c1 = new Child('zhangsan', 20);
var c2 = new Child('lisi', 21);
c1.colors.push('blue');
alert(c1.colors); //red,yellow,blue
c1.sayName(); //zhangsan
c1.sayAge(); //20
alert(c2.colors); //red,yellow
c2.sayName(); //lisi
c2.sayAge(); //21
您可能感兴趣的文章: