Javascript模块多实例
实际上我只是在学习Javascript模块多实例,javascript,jquery,Javascript,Jquery,实际上我只是在学习JavaScript模块。它们非常简单,但当涉及到单个模块的多个实例时,我陷入了困境 这是我的密码 var Mod = (function() { var ops; ops = function () { var Num; this.set = function (e) { Num = e; return this; }; this.get = fun
JavaScript模块
。它们非常简单,但当涉及到单个模块的多个实例时,我陷入了困境
这是我的密码
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();
})();
但当我这么做的时候
console.log(a = Mod.set(1));
console.log(b = Mod.set(2));
console.log(a.get()); // output 2 :'(
console.log(a == b); // true :/
我不明白为什么会这样?可能是因为Mod
匿名函数只调用了一次,但现在我的问题是Jquery$
如何工作?
作为
我该如何用我的Mod实现这种行为呢?我应该使用另一种编程技术吗?但是我不想使用new
关键字提前谢谢!
这是你的电话号码
为什么会这样?可能是因为Mod匿名函数只调用一次
是的,你理解得对。您只有一个实例,即单个对象,因此a
实际上只是b
的另一个名称
但现在我的问题是Jquery$如何工作
jQuery通过使用new
关键字正确地构造新实例(请参见)
UPD.以下是一种正确实例化的方法:
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);
那么如何在这里实现呢?bcoz在jquery中我们不使用new
谢谢jquery代码,但我仍然不知道如何在这里使用它?你能描述一下你想要的代码的预期用途吗?a=Mod,set(1)
和b=Mo.set(2)
应该是不同的;)这就是我想要的
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);