Actually im just studying JavaScript modules. They are pretty easy but i got stuck in when it comes to multiple instances of single module
here is my code
var Mod = (function() {
var ops;
ops = function () {
var Num;
this.set = function (e) {
Num = e;
return this;
};
this.get = function() {
return Num;
};
};
return new ops();
})();
but when i do
console.log(a = Mod.set(1));
console.log(b = Mod.set(2));
console.log(a.get()); // output 2 :'(
console.log(a == b); // true :/
i cant understand why this is happening? may be because Mod anonymous function only call one time but now my question how Jquery $ works?
as
a = $("div")
b = $("span")
console.log(a == b) // false
and how can i achieve this behavior with my Mod should i go for another programming technique? but i dont want to use new keyword thanks in advance!
here is the fiddle
why this is happening? may be because Mod anonymous function only call one time
Yes, you understand it right. You only have one instance, single object, so a is indeed just another name for b.
but now my question how Jquery $ works?
jQuery constructs new instances properly (see the source code), by the way with new keyword which you don't want to use for some reason.
UPD. Here is one approach for correct instantiation:
var Mod = (function() {
function ops(value) {
this.value = value;
}
ops.prototype.get = function() {
return this.value;
};
return {
set: function(value) {
return new ops(value);
}
};
})();
console.log(a = Mod.set(1));
console.log(b = Mod.set(2));
console.log(a.get());
console.log(a === b);
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