原理:
结合了原型链和对象伪装各自优点的方式,基本思路是:使用原型链继承原型上的属性和方法,使用对象伪装继承实例属性,通过定义原型方法,允许函数复用,并运行每个实例拥有自己的属性
function BaseClass(name) {
this.Name = name;
this.colors = ['red', 'blue'];
}
BaseClass.prototype.GetName = function () { return this.Name; }
function ChildClass(name, age) {
this.Age = age;
BaseClass.call(this, name);
}
ChildClass.prototype = new BaseClass();
ChildClass.prototype.GetAge = function () { return this.Age; }
var instance1 = new ChildClass('zhangsan', 15);
var instance2 = new ChildClass('Lisi', 20);
instance2.colors.push('green');
var instance3 = new ChildClass('wangwu', 45);
alert(instance1.colors);
alert(instance1.GetAge());
alert(instance1.GetName());
alert(instance2.colors);
alert(instance2.GetAge());
alert(instance2.GetName());
alert(instance3.colors);
alert(instance3.GetAge());
alert(instance3.GetName());