JS best practice for member functions
Posted
by
MickMalone1983
on Stack Overflow
See other posts from Stack Overflow
or by MickMalone1983
Published on 2013-10-27T03:40:36Z
Indexed on
2013/10/27
3:53 UTC
Read the original article
Hit count: 94
I'm writing a little mobile games library, and I'm not sure the best practice for declaring member functions of instantiated function objects.
For instance, I might create a simple object with one property, and a method to print it:
function Foo(id){
this.id = id;
this.print = function(){
console.log(this.id);
};
};
However, a function which does not need access to 'private' members of the function does not need to be declared in the function at all. I could equally have written:
function print(){
console.log(this.id);
};
function Foo(id){
this.id = id;
this.print = print;
};
When the function is invoked through an instance of Foo, the instance becomes the context for this
, so the output is the same in either case.
I'm not entirely sure how memory is allocated with JS, and I can't find anything that I can understand about something this specific, but it seems to me that with the first example all members of Foo, including the print function, are duplicated each time it is instantiated - but with the second, it just gets a pointer to one, pre-declared function, which would save any more memory having to be allocated as more instances of Foo are created.
Am I correct, and if I am, is there any memory/performance benefit to doing this?
© Stack Overflow or respective owner