//F是空对象,所以几乎不占内存。这时,修改SonType的prototype对象,就不会影响到ParentType的prototype对象。
var F = function(){};
F.prototype = ParentType.prototype;
SonType.prototype = new F();
SonType.prototype.constructor = SonType;
//为子对象设一个uber属性,这个属性直接指向父对象的prototype属性。(uber是一个德语词,意思是"向上"、"上一层"。)这等于在子对象上打开一条通道,可以直接调用父对象的方法。这一行放在这里,只是为了实现继承的完备性,纯属备用性质。
SonType.uber = ParentType.prototype;
function ParentType(name, age) {
this.name = name;
this.age = age;
};
ParentType.prototype.getParentName = function() {
return this.name;
};
ParentType.prototype.getParentAge = function() {
return this.age;
};
ParentType.prototype.ParentPrint = function(_that) {
if(!_that) {
return this.getParentName() + '-' + this.getParentAge();
}else {
return _that.getParentName() + '-' + _that.getParentAge();
}
};
function SonType(name, age, sex) {
ParentType.call(this, name, age); //将父对象的构造函数绑定在子对象上
this.sex = sex;
};
SonType.prototype.getSonSex = function() {
return this.sex;
};
SonType.prototype.SonPrint = function() {
return SonType.uber.ParentPrint(this) + '-' + this.getSonSex();
};
var son = new SonType('Jeremy', 22, '男');
son.SonPrint(); //Jeremy-22-男
原生JS实现类
最新推荐文章于 2024-04-30 16:57:21 发布