What techniques can be used to define a class in JavaScript, and what are their trade-offs?

后端 未结 19 1707
庸人自扰
庸人自扰 2020-11-22 07:26

I prefer to use OOP in large scale projects like the one I\'m working on right now. I need to create several classes in JavaScript but, if I\'m not mistaken, there are at le

19条回答
  •  不知归路
    2020-11-22 08:04

    If you're going for simple, you can avoid the "new" keyword entirely and just use factory methods. I prefer this, sometimes, because I like using JSON to create objects.

    function getSomeObj(var1, var2){
      var obj = {
         instancevar1: var1,
         instancevar2: var2,
         someMethod: function(param)
         {  
              //stuff; 
         }
      };
      return obj;
    }
    
    var myobj = getSomeObj("var1", "var2");
    myobj.someMethod("bla");
    

    I'm not sure what the performance hit is for large objects, though.

提交回复
热议问题