performance - JavaScript "classes" -
Is there a downside to using JavaScript "square" with this pattern?
var FooClass = function () {var personal = "a private variable"; This.public = "a public variable"; Var personalization = function () {...}; This.publicfn = function () {...}; }; Var foo = new FooClass (); Foo.public = "bar"; Foo.publicfn ();
What are you doing in your example "class" pattern people do not have JS Think in - Generally people are thinking of more "normal" class models of Java / C # / C ++ / etc., which can be fake with libraries.
Instead your examples are really quite normal and good JS designs, but for perfection, I will discuss your personal differences between personal and public "members"
< Code> var private = "a private variable"; This.public = "a public variable";Variables.
Accessing
personal
from any of your work will greatly speed up access topublic
becauseis replaced by private With a steady look by JS engine,
can be set correctly; Attempts to reachpublic
need to be seen, most modern JS engines do caching of a degree, But it's still a comparison of simple scoped var access More expensive in.var Privatefn = function () {...}; This.publicfn = function () {...};
The same lookup rule applies to these functions with access to the above variable, only the actual difference (in your example) is that if your function is called, then
Privatefn ()
vsthis.publicfn ()
,privatefn
will always get the global object forthis
. But if anyf = foo.publicfn; F (); Then
will callf this
as a global object, it will be able tof
> PersonalHowever, the more common way to do public actions (which resolves to modify the issue of individual personal members) is to put public functions on the prototype.
Foo.prototype.publicfn = function () {...}
that does not force public actions to modify personal information - There are some times where this is not an option, but it is a good practice because of this the use of memory becomes a bit less:
function Foo1 () {this.f = function () {Return "foo"}; }
vs
function Foo2 () {} Foo2.prototype.f = function () {return "foo"}; In
Foo1
you have a copy of the function object for each instance ofFoo1
(not all emory, objects only, e.g.New Foo1 (). F! == New Foo2 () .f
) whereas inFoo2
there is only one function object.
Comments
Post a Comment