In Javascript, when I want to declare a 'publicly' accessible function what is the idiomatic approach?
MyObj.prototype.foo = function() {
...
}
or
function MyObj() {
this.foo = function() {
...
}
}
What situations would determine one style over the other? What are the advantages of one over the other?
Thanks a bunch for the help!
When a method declared on the prototype it's shared among all instances created by invoking the function as a constructor.
//assuming the first kind
var a = new MyObj();
var b = new MyObj();
//a and b both have the _same_ foo method
On the other hand, when it's created inside the class, each gets its own instance of the function.
//assuming the second kind
var a = new MyObj();
var b = new MyObj();
//a and b both have the _different_ foo methods
Creating things on the prototype is useful for sharing functionality. It's faster than giving each instance its own copy of the method. However, if the construction creates closure the function will have access to it.
You can only access the closure of the creation in the second version
function MyObj(x) {
var y = x;
this.foo = function() {
console.log(y);
}
}
This is not possible in the first version. While this seems silly in this example sometimes closures are very useful. However, since the function now has access to the closure, even if it doesn't use it - it'll be slower. This is insignificant in 99% of cases but in performance intensive situations it might matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With