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.
Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.
Objects created using object literals are singletons. This means when a change is made to the object, it affects that object across the entire script. Object defined with a function constructor let us have multiple instances of that object. This means change made to one instance, will not affect other instances.
Literals represent values in JavaScript. These are fixed values—not variables—that you literally provide in your script.
With the constructor function notation you create an object that can be instantiated into multiple instances (with the new keyword), while the literal notation delivers a single object, like a singleton.
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.
The first one will just create a single object, you can't use it with the new
keyword. The second one contains a local variable a
instead of creating a property like the first one.
Functions are usually written as named functions instead of anonymous functions assigned to variables:
function x() {
this.a = 'a';
this.eat = function() {};
}
Now you can create objects using it:
var y = new x();
Another way of specifying methods for the object is to put it in the prototype:
function x() {
this.a = 'a';
}
x.prototype.eat = function() {};
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