A little lesson in JS objects
-
myobject = function(){
-
// defining a method_1
-
function method_1() {
-
-
function sub_method_1() {
-
// defining some var (sum_method_1_var) that gonna be used only in the sub_method_1
-
var sub_method_1_var = 7;
-
-
// accessing the (z) var thats defined in the method_1
-
// this is only possible because sub_method_1 is a sub method of method_1, where the z var is defined
-
return sub_method_1_var+z;
-
}
-
-
// defining a var (z) that will be used in method_1 but accessible
-
// from each sub method in method_1
-
var z = 1;
-
-
// getting the sum of z + sum_method_1_var ( 1+7)
-
// output: 8
-
var something = sub_method_1();
-
return something;
-
}
-
-
//defing a value with the result from the method_1
-
result = method_1();
-
-
// all the method defined in return {} will be public and accessible for the "outside world"
-
return {
-
// defining a public method
-
public_method : function() {
-
return result;
-
}
-
};
-
}
-
// defining x as myobject
-
x = new myobject();
-
// accessing the public_method of myobject (x)
-
final_result = x.public_method();
-
// alert the result
-
alert(final_result);
A very handy tool for testing pieces of JS source is the Execute JS Add-on for Firefox
It’s the fastest and painless way to execute JS and debug if needed :

I hope this example may help someone


Sorry, comments are closed.