javascript类继承系列五(其他方式继承)

除了前面学习的三种继承外,还有另外三种:
原型继承
寄生继承,
寄生组合继承
都是以:
function object(o) {
function F() { }
F.prototype = o;
return new F();
}
为基础:
先定义的F(),相当于模板类,接着它的原型对象被指向了传入的参数o,F具有了o的属性和方法(作为原型属性和方法)最后返回一个模板类实例

 

var person = { name: 'ads', friends: ['sds1', 'sds2'] };
var other = object(person);
other.showName = function () { return this.name; }
other.showFriends = function () { return this.friends; }
other.name = 'sds3';
other.friends.push('sds4');
alert(other.showName());
alert(other.showFriends());
//other对象的原型是person,即name friends属性是other的原型对象上的属性,
//对它们的改变都影响到其他对象(从person继承的,甚至Person自己)
alert(person.name);
alert(person.friends);
//原型属性的改变将影响其他对象,寄生继承可以看做是对原型继承的增强,它在object()基础上提供了create()

寄生继承的核心代码

function inherit(childType,baseType){//childType:子类构造器,baseType:基类构造器
    var proto = object(baseType.prototype);//基于基类原型对象创建一个对象,将作为子类原型对象
    proto.constructor = childType;//指定新原型对象的构造器属性为子类构造器
    childType.prototype = proto;//子类原型属性指向新的原型对象
}

//create()的用意很明确,相对于object()来说,新对象通过原型继承了o的属性和方法,再定义新对象自己的属性和方法
function inherit(childType,baseType) {//childType:子类构造器,baseType:基类构造器
var proto = object(baseType.prototype);//基于基类原型对象创建一个对象作为子类的原型对象
proto.constructor = childType;//指定新原型对象的构造器属性为子类构造器
childType.prototype = proto;//子类原型属性指向新的原型对象
}

function BaseClass(name) { this.name = name; this.colors = ['blue', 'red']; }
BaseClass.GetName = function () { this.name; }
function ChildClass(name, age) {
BaseClass.apply(this, [name]);
this.age = age;
}
inherit(ChildClass, BaseClass);
ChildClass.prototype.getAge = function () { return this.age; }
var obj = new ChildClass("sds", 50);
alert(obj.getAge());//sds
alert(obj.getAge());//50
alert(obj.colors);//red,blue;

注意:
对象的原型对象上的属性并不是对象自己的属性,但是对象可以通过.或者[]访问,in
操作符可以访问对象上所有能访问的属性和方法,而hasOwnProperty()方法只能检测
对象自身的属性和方法

var one = { 'name': 'ads', 'getName': function () { return this.name; } }
var two = object(one);

alert('name' in one);
alert('name' in two);

alert(two.hasOwnProperty('name'));

 

在对 two.name 赋值操作后,two对象自身会创建一个name属性,有别与two的原型对象上的name属性,从此对two.name的访问或者赋值都使用自身的name属性,与位于原型的name没关系

posted @ 2016-06-20 16:57  那就让我这样吧  阅读(118)  评论(0编辑  收藏  举报