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

后端 未结 19 1456
庸人自扰
庸人自扰 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:00

    The simple way is:

    function Foo(a) {
      var that=this;
    
      function privateMethod() { .. }
    
      // public methods
      that.add = function(b) {
        return a + b;
      };
      that.avg = function(b) {
        return that.add(b) / 2; // calling another public method
      };
    }
    
    var x = new Foo(10);
    alert(x.add(2)); // 12
    alert(x.avg(20)); // 15
    

    The reason for that is that this can be bound to something else if you give a method as an event handler, so you save the value during instantiation and use it later.

    Edit: it's definitely not the best way, just a simple way. I'm waiting for good answers too!

提交回复
热议问题