LoginSignup
24
23

More than 5 years have passed since last update.

jsで軽くクラス書きたい時のClass定義関数

Last updated at Posted at 2014-03-28

========================

jsインラインで済ませたい時に使ってます

使い方

    /**
     * クラスを定義してみる
     */
    var A = Class( Object, {

        /** コンストラクター */
        constructor: function( name ){
            /** @private */
            this._name = name;
        },

        /** プロパティ */
        name: { get: function(){ 
            return this._name; 
        }},

        /** メソッド */
        toString: function(){ 
            return "[object A name=\""+ this.name +"\"]"; 
        }
    });

    /**
     * 継承してみる
     */
    var B = Class( A, {
        constructor: function(){ 
            A.apply( this, arguments ); 
        },

        setName: function( value ){ 
            this._name = value; 
        },

        toString: function(){ 
            return "[object B name=\""+ this.name +"\"]"; 
        }
    });

    // つかってみる
    var a = new A( "aaa" );
    console.log( ""+a ); // "[object A name="aaa"]"

    var b = new B( "aaa" );
    console.log( ""+b ); // "[object B name="aaa"]"

    b.setName( "bbb" );
    console.log( ""+b ); // "[object B name="bbb"]"

ソース


    /** クラス */
    function Class(){
        if( arguments.length>= 2 ) {
            var impl=arguments[1],work={};
            for( var k in impl ) ( typeof impl[k] === "function" )? work[k]={ value:impl[k], writable:true }: work[k]=impl[k];
            var constructor = work.constructor.value;
            constructor.prototype = Object.create( arguments[0].prototype, work );
            return constructor;
        }
        throw new Error("");
    };

※{writable: true}追加したほうがいいかもしれません

24
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
23