after experimenting with js’s prototypal inheritance i’ve found that i’m not wild about the idea of having to declare my object’s methods outside of the object:
function obj(){
this.averyday='i\'m shuffle\'n';
this.gibmo='dinero';
this.pullOut='that\'s what she said lol';
}
obj.prototype.alertProp=function(){
alert(this.averyday);
}
obj.prototype.alertProp2=function(){
alert(this.gibmo);
}
so i came up with a way to organize my methods into one namespace
obj.prototype.m={
//i'm passing in the object instance so the mathods can have access to it's properties
alertProp:function(that){
alert(that.theObj.everyday);
},
alertProp2:function(that){
alert(that.myObj.gibmo+' '+that.myObj.someVal); // alerts "dinero some other value to be use "
}
}
var myobj = new obj;
then to use i just call the method and pass in the objects instance(if the method needs to modify the object’s properties)
myobj.m.alertProp({theObj:myobj,someVal:'some other value to be use'}) //alerts "i'm shuffle'n"
so here are some pros that i’ve noticed:
PROS:
1) organizes the methods into one centralized area.
2) accesses the “prototype” of an object only once(in effect uses less code).
3) seems more readable(at lease to me).
CONS:…this is where i need you’alls help, does anyone see anything wrong with doing it this way? any performance issues or anything wrong with the pros i’ve outlined etc…?
also does anyone see any other pros that i may not be seeing or that aren’t apparent?
I find it a little bit complicated, this is how I like to do it:
So you don’t have to worry about sending extra parameters, you just call it.
—————————-EDIT———————————
Well, I don’t know if I got it right, but after some reading I believe this would “fixing the constructor” mean. If I create an object like this:
Then
Foo.prototype.constructor == Foo, as one would expect.The problem with my method (thanks Raynos) is that when I’m doing this:
I’m overwriting all of Foo’s prototype, so that
Foo.property.constructor != Foo, and that is not what we would expect! Instead of that we have thatFoo.property.constructor == Object.prototype.constructor.So, how we fix it?
Ta da!
(this helped a lot: http://beej.us/blog/data/javascript-prototypes-inheritance/ )