Search Results

Search found 1 results on 1 pages for 'mickmalone1983'.

Page 1/1 | 1 

  • JS best practice for member functions

    - by MickMalone1983
    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?

    Read the article

1