Constructors in JavaScript objects

后端 未结 19 1747
夕颜
夕颜 2020-11-22 10:21

Can JavaScript classes/objects have constructors? How are they created?

19条回答
  •  心在旅途
    2020-11-22 10:34

    I guess I'll post what I do with javascript closure since no one is using closure yet.

    var user = function(id) {
      // private properties & methods goes here.
      var someValue;
      function doSomething(data) {
        someValue = data;
      };
    
      // constructor goes here.
      if (!id) return null;
    
      // public properties & methods goes here.
      return {
        id: id,
        method: function(params) {
          doSomething(params);
        }
      };
    };
    

    Comments and suggestions to this solution are welcome. :)

提交回复
热议问题