I have the following javascript :
var MyObject = (function() {
function Setup(args) {
this.prop1 = args.x;
this.prop2 = args.y
this.prop3 = this.prop1 + this.prop2;
this.Create = function() {
return 'a' + helperFunc();
}
function helperFunc() {
return this.prop3;
}
}
return {
init : function(args) {
var setup = new Setup(args);
setup.Create();
}
}
})();
$(function() {
MyObject.init(someArgs);
});
Is my approach to object construction a good practice?
I am getting undefined
in the helperFunc when trying to access this.prop3
.
I have also tried to assign this.prop1 + this.prop2
to a local variable and use a function to return this value like so:
function Setup(args) {
var total;
this.prop1 = args.x;
this.prop2 = args.y
total = this.prop1 + this.prop2;
this.getTotal = function() {
return total;
};
this.prop3 = this.prop1 + this.prop2;
...
...and when calling this in the helperFunc like this:
return this.getTotal();
.. i get this.getTotal
is not a function
I have been reading around object creation and using closures to mimic private members and so on and since there is no one way to define objects I am getting confused.
TBH - I don't really understand the construct:
var myObject = (function() { ... } ();
I've seen it used a lot in jQuery plugins but what does the first parenth followed by empty parenth at the end mean and do?
Any knowledge imparted would be much appreciated.
Also, I have on order the Douglas Crockford book on javascript and until it arrives I need to try to solve this problem
Using an Object Literal This is the easiest way to create a JavaScript Object. Using an object literal, you both define and create an object in one statement. An object literal is a list of name:value pairs (like age:50) inside curly braces {}.
Avoid globals. Global variables and function names are an incredibly bad idea. The reason is that every JavaScript file included in the page runs in the same scope.
It means you are alerting an instance of an object.
The syntax of creating object directly is given below: var objectname=new Object();
To cite Xhalent's wonderful article (really well done and clearly wirtten) mentioned by him:
That is because the value of “this” is different to the value of “this” when the object was created.
So in your case:
...
var _this = this.prop3;
function helperFunc() {
return _this;
}
...
might achieve what's desired.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With