whats the best practice to use these?
var x = { a: 'a', eat: function()开发者_如何学JAVA { }, ... }
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.
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() {};
Generally it depend on what you are trying to get. Remember, that JS has no real classes, its prototype based language. Operator new
is quite misleading.
I would suggest using literal {}
whenever it is possible. In example, you could do it like this:
var myconstr = function(param){
var pr = 'some private var';
return {
a : param,
get2a : function(){ return this.a; }
};
};
If you want only one instance, you could always call this function just after defining it.
BUT if you want to use prototype
, it could be easier with Construction function - but still, i wouldn't use new operator as is, maybe wrapping it in some other func would be better.
精彩评论