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 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: Called like: 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 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: The call is now cleaner: 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 ).
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}; };
someNiceMap.addPoint (point ({x: 2, color: "red"}); someNiceMap.addPoint (Point ({X: 14});
this is the inability to mention the newly created object.
< Code> var point = {create: function (opts) {... return {_isAPoint: true, color: opts.color, x: opt S.x};}}
someNiceMap.addPoint (Point.create (...));
Comments
Post a Comment