Different things for different uses.
Ray wrote:
Hello,
While reading another guy's I found myself a bit confused by his way of
declaring his class--I usually declare a class like this:
function Foo() {
this.blah = true;
this.bleh = false;
}
Foo.prototype.blabla = function() {
};
With this technique you can make lots of foo (really instances of Foo).
var a = new Foo();
var b = new Foo();
You could also create a Foo sorting function:
function fooSort(foo1,foo2){
var comp = 0;
if(foo1.blah && !foo2.blah){
comp = (-1);
} else if(!foo1.blah && foo2.blah){
comp = (1);
}
return comp;
}
and sort an array of foo:
var a = new Foo();
var b = new Foo();
b.blah = false;
var c = new Foo();
var fooArray = new Array(a,b,c);
fooArray.sort(fooSort);
Some might avoid prototype using a form like:
function Foo() {
this.blah = true;
this.bleh = false;
this.blabla = function() {
};
arguments.callee.fooSorter = function fooSort(foo1,foo2){
var comp = 0;
if(foo1.blah && !foo2.blah){
comp = (-1);
} else if(!foo1.blah && foo2.blah){
comp = (1);
}
return comp;
}
}
// test
var a = new Foo();
var b = new Foo();
b.blah = false;
var c = new Foo();
fooArray.sort(Foo.fooSorter);
var res = "";
for(var i=0;i<fooArray.length;i++){
res += fooArray[i].blah + "\n";
}
alert(res);
>
and so on. However in his code he does a lot of this:
var Foo = {
blah : true,
bleh : false,
blabla : function() {
}
};
This form is used to create a single object. It is also useful for many
things.
If you only need one, then this is more concise.
>
My question is, how are they different? I mean I guess he's declaring
his class JSON style. But can he even do a new() on his class? Seems
like then he's limited to using his methods and variables statically,
e.g.: Foo.blah, Foo.bleh, Foo.blabla() and so on.
Is there any particular reason why one would do that?
Let the flame wars commence... ;-)
>
Thank you!
Ray