2017-02-10 10 views
0

私は以下の構造でjavascriptクラスオブジェクトを作成しています。これを達成するより良い方法はありますか?javascript:クラスを作成する最良の方法

function MyClass(config) 
{ 
    this.init(config); 
} 

MyClass.prototype = 
{ 
    that:this, 
    config:null, 

    init:function(config) 
    { 
     this.config = config; 
     this.blah(); 
    }, 

    blah:function() 
    { 
     if(this.config.blah) 
     { 
      console.log(this.config.blah) 
     } 
    } 
} 

new MyClass({blah:"helloWorld"}); 
+4

"ベター" は常に議論の余地があります。私は、あなたが 'that'と' config'をインスタンスそのものではなくプロトタイプの上に直接置くという作業だと思います。それをサポートするブラウザで['class'構文](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)を使用することができます。本当に、それはちょうどあなたにとって最善のものです。 –

答えて

1

個人的には、クラスのすべてのコンテンツをエンクロージャに格納することをお勧めします。

thatあなたの例ではMyClassインスタンスが設定されていません。

var MyClass = (function() { 

    var MyClass = function (config) { 

     // Optional check whether the class was accessed using new 
     if (!(this instanceof MyClass)) 
      throw new Error('You must create the instance using the keyword new'); 

     // Don't add it to the prototype as it is unique to the instance 
     this.config = config; 

     this.blah(); 
    }; 

    MyClass.prototype = { 

     blah: function() { 

      if (this.config.blah) 
       console.log(this.config.blah); 
     } 
    }; 

    return MyClass; 

})(); 

// That has the instance now 
var that = new MyClass ({ 
    blah: 'helloWorld' 
}); 

あなたが試みることができるよりも、あなたがES6を使用することができる場合:

class MyClass { 

    constructor (config) { 

     // Don't add it to the prototype as it is unique to the instance 
     this.config = config; 

     this.blah(); 
    } 

    get config() { 
     return this._config; 
    } 

    set config (value) { 
     this._config = value; 
    } 

    blah() { 

     if (this.config.blah) 
      console.log(this.config.blah); 
    } 
} 

let that = new MyClass({ 
    blah: 'helloWorld' 
}); 
+0

これは私が探していたガイダンスです。 – K3NN3TH

0
function MyClass(config) { 
    // Define any Class methods, private or exposed. 
    var blah = function() { 
    if (this.config.blah) { console.log(this.config.blah); } 
    } 

    // Set your class properties. 
    this.config = config; 

    // Invoke any of the functions defined above that should be run on 
    // init, using .apply(this) for logical scoping. 
    blah.apply(this); 

    // Expose any props or methods that you want to. 
    return { 
    config: config, 
    blah: blah 
    }; 
} 

new MyClass({blah: 'blah'}); 
関連する問題