How to create OOP Class in Javascript

后端 未结 3 1716
闹比i
闹比i 2021-01-16 05:59

I\'m hesitant to use just any tutorial because I know how those tutorials can end up being, teaching you bad ways to do things. I want to setup a class in Javascript, so th

3条回答
  •  伪装坚强ぢ
    2021-01-16 06:16

    Although there are no classes in JavaScript, you can create constructor functions. A constructor function works by binding methods to an objects prototype. There are several ways to do this, each with advantages and disadvantages. I personally prefer the most straigthforward way, which works by appending methods to "this":

    var Constructor = function() {
    
      //object properties can be declared directly
      this.property = "value";
    
      //to add a method simply use dot notation to assign an anonymous function to an object
      //property
      this.method = function () {
        //some code
      }
    
      //you can even add private functions here. This function will only be visible to this object methods
      function private() {
        //some code
      }
      //use return this at the end to allow chaining like in var object = new Constructor().method();
      return this; 
    
    }
    

提交回复
热议问题