JavaScript constructors using JavaScript object literal notation

前端 未结 6 1827
半阙折子戏
半阙折子戏 2021-01-30 15:30

What is the best way to build constructors in JavaScript using object literal notation?

var myObject = {
 funca : function() {
  //...
 },

 funcb : function() {         


        
6条回答
  •  情话喂你
    2021-01-30 15:32

    Make the object a function, like this:

    var myObject = function(arg1){
      this.funca = function(){
        //...
      };
      this.funcb = function(){
        //...
      };
      this.constructor = function(obj){
        alert('constructor! I can now use the arg: ' + obj.name);
      };
      this.constructor(arg1);
    };
    
    // Use the object, passing in an initializer:
    var myVar = new myObject({ name: 'Doug'});
    

提交回复
热议问题