精通Javascript中的一段代码不太懂,麻烦大神帮我看看
一段用于实现继承的代码,有两处不太明白, 不明白的地方我写在代码的注释中了
classDifination是一个对象直接量,该对象包含新对象的属性和方法, parentProto是要继承的父类对象原型
var Class = (function (){
function create(classDifination, parentProto){
var _NewClass = function (){
if(this.initialize && typeof this.initialize === 'function'){
this.initialize.call(this, arguments);
}
},
_name;
if(parentProto){
//这里用了原型继承,下面为什么还要再拷贝一次?
_NewClass.prototype = new parentProto.constructor();
for(_name in parentProto){
if(parentProto.hasOwnProperty[_name]){
_NewClass.prototype[_name] = parentProto[_name];
}
}
}
// 模拟多态
function polymorph(thisFunction, parentFunction){
return function (){
var output;
// 这个this.__parent在这里做了什么?
this.__parent = parentFunction;
output = thisFunction.apply(this, arguments);
delete this.__parent;
return output;
};
}
for(_name in classDifination){
if(classDifination.hasOwnProperty(_name)){
if(parentProto[_name] && classDifination[_name] && typeof classDifination[_name] === 'function'){
_NewClass.prototype[_name] = polymorph(classDifination[_name], parentProto[_name]);
}else{
_NewClass.prototype[_name] = classDifination[_name];
}
}
}
_NewClass.prototype.constructor = _NewClass;
_NewClass.prototype.extend = extend;
return _NewClass;
}
function extend(classDifination){
return create(classDifination, this.prototype);
}
return {
create: create
};
}());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
_NewClass
的原型是用parentProto
的构造函数创建的对象,不是parentProto
对象,所以还要再把parentProto
中的属性拷贝一次就是让你在继承后的子类方法中可以用
this.__parent()
来访问父类的同名方法。这个this.__parent
是每次调用子类的方法时自动创建的,方法执行完之后就删除,所以其他代码不能用这个属性(也就是说,仅在该子类的方法内部才能使用)给你一个简单的例子
之前没有认真看,在写例子的过程中发现你给的那个代码里有不少问题,不知道是你贴错了还是原本就有问题。
下面是例子。具体参照里面的注释