The difference between putting functions into an object and prototyping them?
What's the difference between adding functi开发者_如何学JAVAons to an object and prototyping them onto the object?
Prototyping allows the object/model to call itself?
An "object of functions" is typically used to "namespace" a set of functions so that there is one container object with numerous methods rather than numerous global functions. The benefit is in keep code components categorised or grouped by the object (and perhaps an object hierarchy), there are no benefits to performance and if global functions are thoughtfully named, there should be no reasonable chance of a naming collision. That is, the primary purpose is to create neat, logical groups of functions.
By "prototyping methods" I presume you mean using a constructor to create instances. Constructors and prototypes are used where inheritance is required, they are quite a different strategy to "namespaceing", the use of one does not preclude the other. It is quite reasonable to use prototypes for inheritance and use an "object of functions" to group the instances (and constructors for that matter).
Here is coding example.
// when defining "Bla", the initial definition is copied into the "prototype"
var Bla = function()
{
this.a = 1;
}
// we can either modify the "prototype" of "Bla"
Bla.prototype.b = 2;
// or we can modify the instance of "Bla"
Bla.c = 3;
// now lets experiment with this..
var x = new Bla(); // read: "clone the prototype of 'Bla' into variable 'x'"
alert(x.b); // alerts "2"
alert(x.c); // undefined -- because "c" doesn't exist in the prototype
alert(Bla.c); // alerts "3" -- "Bla" is an object, just like your instance 'x'
// also note this:
Bla.a = 1337;
var y = new Bla();
alert (y.a); // alerts "1" -- because the initial definition was cloned,
// opposed to the current state of object "Bla"
精彩评论