javascript - Simple object "construction" (without prototypal inheritance) -


I wrote a function object only as a logic, and naturally I need an object that A specific object specification (what kind of properties it is, etc.).

Rather than passing it as an object, instead of doing all the testing inside the function, I had to write the "constructor" function which you pass is a literal object, and that object specification will be applied All works, and provides the default value if necessary.

This function will not be called from new because it has no prototype legacy required. The special property ( _isAPoint ) may be included in the return item to "prove" that the object was properly created (a replacement for instanceof ).

I do not remember seeing this kind of approach before. At first glance, it is a clear way to create proper logic objects, while avoiding the entire system of prototype heritage.

What do you think? Is this an identity pattern? Can you tell me about possible flaws and improvements?

Simple example:

  var point = function {opts} {"strict experiment"; Var default = {color: "blue", X: 0}; Opts = $ .extend (default, opts); // (using jQuery extension) if (! IsNan x) {new error ("x should be a number"); } Return {_isapoint: true, color: opts.color, x: opts.x}; };   

Called like:

  someNiceMap.addPoint (point ({x: 2, color: "red"}); someNiceMap.addPoint (Point ({X: 14});    

The factory method that you show The pattern is called

There is no fundamental flaw in this approach and it is considered as an option for constructor pattern.

This blog entry by both professionals and opposition by Eric Elliott Presented in: / P>

h As you can see, the only major drawback is that the use of this is the inability to mention the newly created object.

But is this a flaw? ? Warned that Eric is known to go against the Constructor functions in favor of factory methods.

To make your code cleaner, make the factory clear the law:

 < Code> var point = {create: function (opts) {... return {_isAPoint: true, color: opts.color, x: opt S.x};}}   

The call is now cleaner:

  someNiceMap.addPoint (Point.create (...));    

Comments

Popular posts from this blog

c - Mpirun hangs when mpi send and recieve is put in a loop -

python - Apply coupon to a customer's subscription based on non-stripe related actions on the site -

java - Unable to get JDBC connection in Spring application to MySQL -