0
我一直在我的网络应用中使用John Resig javascript class implementation,但测试显示它非常慢。我真的觉得它对于扩展对象的方式很有用,并且从更好的代码和更少的冗余中获得好处。在JavaScript中实现简单继承
在某些文章中解释说,由于处理_super
方法的原因,速度很慢。 由于super
是Java风格,并且大部分时间我都是用PHP开发的,所以我使用parent::
样式(在PHP中使用)制作了我自己的Resig实现版本,旨在使其更快。那就是:
(function() {
this.Class = function() {
};
Class.extend = function extend(prop) {
var prototype = new this();
prototype.parent = this.prototype;
for (var name in prop) {
prototype[name] = prop[name];
}
function Class() {
this.construct.apply(this, arguments);
}
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.extend = extend;
return Class;
};
})();
使用案例:
var Person = Class.extend({
construct: function (name) {
this.name = name;
},
say: function() {
console.log('I am person: '+this.name);
},
});
var Student = Person.extend({
construct: function (name, mark) {
this.parent.construct.call(this, name);
this.mark = 5;
},
say: function() {
this.parent.say();
console.log('And a student');
},
getMark: function(){
console.log(this.mark);
}
});
var me = new Student('Alban');
me.say();
me.getMark();
console.log(me instanceof Person);
console.log(me instanceof Student);
这方面有任何意见?我这样快吗?正确性怎么样?
此问题似乎是脱离主题,因为它要求[代码审查](http://codereview.stackexchange.com/)。 – Quentin
是的,如果你可以将它移动到正确的部分会更好 – albanx
@Quentin我把它移到这里http://codereview.stackexchange.com/questions/77592/implementing-simple-and-fast-inheritance-in- JavaScript的。你有什么想法? – albanx