I normally use simple objects like this:
var Test = {
value: '', // A value
init: function(options) {
// Set value
Test.value = options.value;
}
};
The problem is when I want to use that object more than once on a page. It overwrites itself. E.g:
Test.init({ "value" : "a" });
// Test.value is now "a"
Test.init({ "value" : "b" });
// Test.value is now "b"
This is why I've turned to the new constructor in JavaScript so I can keep the contents of the constructor separate. I am totally new to JavaScript constructors and whether or not this is the correct way to go about it, I am not sure.
I now have it set-up to run like this:
var first = new Test();
first.init({ "value" : "a" });
// first.value is now "a"
var second = new Test();
second.init({ "value" : "b" });
// second.value is now "a"
My problem now is when using this.value
inside the constructor.
Here is an example of what I mean. You'll see I set this.value
in the init()
function. However, when you create a JQuery loop using it's $.each()
function, this
is overwritten by JQuery so I cannot access the this.value
variable or the this.format()
function.
function Test() {
this.value = '';
}
Test.prototype = {
// Loader
init: function(options) {
// Set value
this.value = options.value;
// This outputs fine
console.log(this.value);
// I'll now create a loop using the JQuery "each" function
$('li').each(function() {
// This fails because "this" has now been overwritten by JQuery inside this function
this.format($(this).attr('data-id'), this.value);
});
},
// Format output
format: function(id, value) {
console.log(id + ' : ' + value);
}
};
var first = new Test();
first.init({ "value" : "a" });
var second = new Test();
second.init({ "value" : "b" });
Here is an example of what error occurs when it is run:
https://jsfiddle.net/8m46u73k/2/
So two questions:
- Am I going about this the right way?
- How do I get access to functions and variables without using
this
?