Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript modules multiple instance

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

like image 764
maq Avatar asked Sep 02 '26 23:09

maq


1 Answers

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);
like image 126
dfsq Avatar answered Sep 05 '26 12:09

dfsq