Constructors in JavaScript objects

2018-12-31 09:30发布

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

19条回答
伤终究还是伤i
2楼-- · 2018-12-31 10:15

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. :)

查看更多
登录 后发表回答