DRY-er Javascript Class

Using jQuery, this is the format of most classes that I write in JS:

$.Tabs = function(options){
var self = this;
this.defaults = {};
var cfg = $.extend(true, {}, this.defaults, options);
this.$elem = cfg.$elem;

function _init(){
    var dontInit = false;

    if (!cfg.$elem || !cfg.requiredProperty){
        alert('missing params');
        dontInit = true;
    }

    if (!dontInit){
        self.$elem.bridge(self);
    }
}

this.show = function(){};
this.hide = function(){};

_init();
}

The code above is just an example.

My question is: how do you extrapolate ordinary tasks / functions from your classes, so that every new class that you write, you do not need to repeat everything again?

I created creating a script class based on John Resig A simple Javascript inheritance template that allows you to require specific parameters, bind event listeners for the pub / sub template, automatically combine the default values ​​with the passed parameters and create a bridge between the DOM element and the class instance (for example, $ ('elem'). data ('instanceNamespace', classInstance);)

script , . , , , , .

? Javascript?

.

: - script ? , , , ?

+3
1

, , , Mix-in.

:, , javascript, jQuery, , , mixins.

, :

var Person = function(name){
    this.name=name;
    this.sayhello = function(){
        console.log(this.name + ' says hello');
    };
};

, :

var extend = function(destination, source) {
    for (var property in source)
        destination[property] = source[property];
    return destination;
};

, , , , , , :

var DanceMixin = {
    dance: function(){
        console.log(this.name + ' is dancing!');
    }
};

var SingMixin = {
    sing: function(){
        console.log(this.name + ' is singing!');
    }
};

var bob = new Person('bob'); 
extend(bob, SingMixin);
extend(bob, DanceMixin);

bob.sing();
/* bob is singing! */
bob.dance();
/* bob is dancing! */
bob.sayhello();
/* bob says hello */

, . Person, Person.

, :

var Animal = function(name){
    this.name = name;
    this.roar = function(){
        console.log(this.name + ' is roaring!');
    };
};

, , . DanceMixin Animal, :

var mixin = function(dest, src){
    for (var property in src)
        dest.prototype[property] = src[property];
    return dest;
}
mixin(Animal, DanceMixin);

, ...

var lion = new Animal('lion');
lion.dance()
/* lion is dancing! */

, MooTools , . Implements MooTools mixins.

+5

Source: https://habr.com/ru/post/1768149/


All Articles