views:

49

answers:

2

Possible Duplicate:
JavaScript: Setting methods through prototype object or in constructor, difference?

I guess this is a question about the browsers implementation of closures really. I know about the numerous ways to emulate Class-like functionality within JavaScript including using various libraries. This is more a question about resources.

Does creating a function in this manner create a new copy of public_function function each time it is called? the underlying question is: Does doing it this way use more RAM than adding the function to MyObject.prototype ?

function MyObject(){
  this.public_function = function(){
    //... do something
  }
}
+2  A: 

Yes.

If nothing else, this requires a slot on every object created by new MyObject() rather than a single slot on the prototype.

But of course, there is something else: the anonymous function creates a closure, capturing the scope in which it is defined. And again, that has to be stored for every object created by MyObject.

Whether this actually matters will depend on how many objects you create...

See also:

Shog9
A: 

For a class that has mulitipul instances, an anonymous function defined in constructor will create a new copy of function for each instance.

another way without using prototype is that define a static function and assign it to the member. For example:

function A(){
    this.hello = Hello;
}

function Hello(){
    alert('hello');
}
Cauly