2015-01-15 53 views
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); 

这方面有任何意见?我这样快吗?正确性怎么样?

+1

此问题似乎是脱离主题,因为它要求[代码审查](http://codereview.stackexchange.com/)。 – Quentin

+0

是的,如果你可以将它移动到正确的部分会更好 – albanx

+0

@Quentin我把它移到这里http://codereview.stackexchange.com/questions/77592/implementing-simple-and-fast-inheritance-in- JavaScript的。你有什么想法? – albanx

回答

-1

在一个乍一看,这看起来还不错:),但我认为做的CoffeeScript实施是目前国内最先进的之一:

class Person 
    walk: -> 
    return 

class myPerson extends Person 
    constructor: -> 
    super 

翻译成这样:

var Person, myPerson, 
    __hasProp = {}.hasOwnProperty, 
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; 

Person = (function() { 
    function Person() {} 

    Person.prototype.walk = function() {}; 

    return Person; 

})(); 

myPerson = (function(_super) { 
    __extends(myPerson, _super); 

    function myPerson() { 
    myPerson.__super__.constructor.apply(this, arguments); 
    } 

    return myPerson; 

})(Person); 

它速度快,干净并且自己进行属性检查。