2015-01-15 2 views
0

Я использую John Resig javascript class implementation в своих веб-приложениях, но тесты показывают, что он очень медленный. Я действительно считаю это полезным для способа расширения объектов, а преимущества получаются из-за лучшего кода и меньшей избыточности.Выполнение простого наследования в JavaScript

В некоторых сообщениях было объяснено, что он был медленным из-за того, как обрабатывается метод _super. С является стилем Java, и большую часть времени, которое я разрабатываю в PHP, я сделал свою собственную версию реализации Resig с использованием стиля parent:: (используется в PHP) с целью сделать это быстрее. Вот оно:

(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); 

Он быстрый, чистый и имеет собственную проверку свойств.

Смежные вопросы