структура наследования javascript - PullRequest
6 голосов
/ 23 февраля 2012

Существует ли небольшое, легкое решение для наследования классов javascript, которое будет хорошо работать как на стороне клиента, так и на стороне сервера (node.js)? Мне не нужна большая библиотека, просто что-то, что позволит мне объявить конструктор и некоторые методы, а затем иметь возможность для класса наследовать это.

Ответы [ 6 ]

6 голосов
/ 23 февраля 2012

Джон Резиг обрисовывает в общих чертах простую структуру наследования приблизительно в 25 строках кода здесь .Я видел, как это было полезно.

Вы можете использовать это так:

var Vehicle = Class.extend({
  init: function(wheels) {
    this.wheels = wheels;
  }
});

var Truck = Vehicle.extend({
  init: function(hp, wheels) {
    this.horsepower = hp;
    this._super(wheels);
  },

  printInfo: function() {
    console.log('I am a truck and I have ' + this.horsepower + ' hp.');
  }
});

var t = new Truck(4, 350);
t.printInfo();
3 голосов
/ 23 февраля 2012

взгляните на https://github.com/ded/klass

1 голос
/ 19 декабря 2012

Я создал эту небольшую библиотеку, чтобы использовать ExtJs Style ClassManager. Пока все довольно просто, но очень гибко.

Установка через node.js

npm install esf-core

Sample

Esf.define('A', {
    a: null,

    constructor: function (a) {
        // Save var
        this.a = a;

        // Heyho
        console.log('A');
    },
    foo: function (b) {
        console.log('foo - ' + b);
    }
});

Esf.define('B', {
    b: null,

    constructor: function (a, b) {
        // Call super constructor
        this.callParent(a);

        // Save var
        this.b = b;

        // Heyho
        console.log('B');
    },
    foo: function () {
        this.callParent('bar');
    }
}, {
    extend: 'A'
});

// Use
var b = new B(1, 2);

// or
var b = Esf.create('B', 1, 2);

/*
 * Output:
 * A
 * B
 * foo - bar
 */
b.foo();

Репозиторий

https://bitbucket.org/tehrengruber/esf-js-core

0 голосов
/ 10 сентября 2013

Я создал очень легкую библиотеку, которая работает в браузере и в файле node.js. Это супер простая в использовании библиотека без раздувания:

Пример:

var Person = proto(function() {       // prototype builder
    this.init = function(legs, arms) {      // constructor
        this.legs = legs
        this.arms = arms
    }

    this.getCaughtInBearTrap = function() { // instance method
        this.legs -= 1
    }
    this.limbs = function() {
        return this.arms + this.legs
    }
})

var Girl = proto(Person, function() { // inheritance
    this.haveBaby = function() {
        return Person(2,2)
    }
})

var g = Girl(2,2)        // instantiation
g.getCaughtInBearTrap()
console.log("Girl has "+g.limbs()+" limbs")
console.log(": (")
0 голосов
/ 17 сентября 2012

Я думаю, что это намного лучше, чем init hax в простом наследовании fw:

(function() {
    var core = {
        require : function(source) {
            if ( typeof (source) != "object" || !source)
                throw new TypeError("Object needed as source.");
            for (var property in source)
                if (source.hasOwnProperty(property) && !this.prototype.hasOwnProperty(property))
                    this.prototype[property] = source[property];
        },
        override : function(source) {
            if ( typeof (source) != "object" || !source)
                throw new TypeError("Object needed as source.");
            for (var property in source)
                if (source.hasOwnProperty(property))
                    this.prototype[property] = source[property];
        },
        extend : function(source) {
            var superClass = this;
            var newClass = source.hasOwnProperty("constructor") ? source.constructor : function() {
                superClass.apply(this, arguments);
            };
            newClass.superClass = superClass;

            var superClone = function() {
            };
            superClone.prototype = superClass.prototype;
            newClass.prototype = new superClone();
            newClass.prototype.constructor = newClass;

            if (source)
                newClass.override(source);
            return newClass;
        }
    };

    core.require.call(Function, core);

    Function.create = function (source){
        var newClass = source.hasOwnProperty("constructor") ? source.constructor : function() {};
        newClass.override(source);
        return newClass;
    };
})(); 

Пример транспортного средства с этим:

var Vehicle = Function.create({
    constructor : function(wheels) {
        this.wheels = wheels;
    }
});

var Truck = Vehicle.extend({
    constructor : function(hp, wheels) {
        this.horsepower = hp;
        Vehicle.call(this, wheels);
    },
    printInfo : function() {
        console.log('I am a truck and I have ' + this.horsepower + ' hp.');
    }
});

var t = new Truck(4, 350);
t.printInfo();
0 голосов
/ 23 февраля 2012

Я видел, как прототип библиотека успешно использовалась.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...