I’ve started writing a lot more javascript lately and am trying to do it all in the best way I can. Formatting my classes using JSON seems to be the cleanest way but I’m having trouble with something that seems like it should be really basic, but I just struggle to find the answer anywhere… perhaps merely from a lack of the right jargon!
So far I’ve been doing things in this method:
function foo(){
this.bar = 'hello world';
this.init = function(){
alert('this.bar');
}
}
crow = new foo();
crow.init();
And that all seems to work as I expect it to. When I lay out the object in JSON though I can’t see to create a new instance of it, only a reference to the original which defeats the point of a lot of uses for me. What am I doing wrong here?
foo = {
bar = 'hello world';
init: function(){
alert(bar);
}
}
foo.bar(); // This alerts 'hello world'
crow = foo ;
crow.bar = 'metal' ;
crow.init(); // Outputs 'metal'
foo.init(); // Also outputs 'metal'
Have I missed the point somewhere, is this the wrong approach or am I just doing it wrong?
If you want to define the functions in a class as an object you need to alter the prototype of the function. Here is an example from your code:
While it is essential to understand how this works if you are using javascript, John Resig has a small script that is fantastic for adding oop features in javascript. This addition allows a psedo-inheritance with the use of a constructor and super functions.