whats the best practice to use these?
var x = { a: 'a', eat: function() { }, ... }
vs
var x = function() { var a = 'a'; this.eat = function() { }}
the above needs to be initiated:
new x();
can someone help me explain the importance of the two, and which one is preferred choice within the oop community? any word of wisdom would help. i also did some research but nothing came up. much thought is appreciated.
The basic difference is that the first version exposes the variable 'a', while the second one hides it. So unless you want or need client code to access x.a
, the second version is preferred.
A third approach would be to use a prototype. In this case, a local variable in the constructor won't do you much good, so if eat()
needs access to a
, then you'd write:
function x() {
this.a = 'a';
}
x.prototype.eat = function() {
// do stuff with this.a
}
In this case, each instance has a new copy of a
, but there's only one copy of eat
. The drawback (if you consider it one) is that a
is available to users of x
instances.