『MVCベースJavaScript Web富応用開発』読書ノート一:MVCとクラス

5035 ワード

クリアークラス:
var Class = function(parent){

    var klass = function(){

        this.init.apply(this, arguments);

    };



    if(parent) {

        var subclass = function(){};

        subclass.prototype = parent.prototype;

        klass.prototype = new subclass;

    }



    klass.prototype.init = function(){};

    klass.fn = klass.prototype;

    klass.fn.parent = klass;



    klass.proxy = function(func){

        var self = this;

        return (function(){

            func.apply(self, arguments);

        });

    };



    klass.fn.proxy = klass.proxy;



    klass.extend = function(obj){

        var extended = obj.extended;

        for(var i in obj){

            klass[i] = obj[i];

        }

        if (extended) extended(klass)

    };



    klass.include = function(obj){

        var included = obj.included;

        for(var i in obj){

            klass.fn[i] = obj[i];

        }

        if (included) included(klass)

    };



    return klass;

};
デモ:
var Person = new Class;

Person.include({

    init: function(name, age){

        this.name = name;

        this.age = Person.checkAge(age) ? age : null;

    },

    sayHello: function(){

        console.log("Hi , My name is " + this.name + (this.age ? ", i am " + this.age + " years old this year" : ""));

    }

});



Person.extend({

    needWater: true,

    checkAge: function(age){

        return age>0 && age < 150;

    }

});



var jim = new Person("Jim", 10);

jim.sayHello();

//output:Hi , My name is Jim, i am 10 years old this year



var tom = new Person("Tom", -1);

tom.sayHello();

//output:Hi , My name is Tom
extedでは静的性質と方法であり、includeでは例示的な属性と方法である.
属性および方法が特定のインスタンスに関係なく、または共通である場合、静的属性および方法を使用して、そうでなければ、例示的な属性および方法を使用する.