2017-02-10 173 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

這是我正在尋找的指導,ty – 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'});