2017-02-10 127 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'}); 
相关问题