[英]Why does this javascript object behave differently with and without a module pattern?
I have the following code with and without a module pattern. 我有以下代码,有和没有模块模式。 I have given the results right next to the execution.
我已经在执行旁边给出了结果。 In the module pattern, I am able to change foo and set_inner, while in the function object (non-module), I can't change foo and set_inner.
在模块模式中,我能够更改foo和set_inner,而在函数对象(非模块)中,我无法更改foo和set_inner。
module pattern:
var someObj = (function () {
var instance = {},
inner = 'some value';
instance.foo = 'blah';
instance.get_inner = function () {
return inner; };
instance.set_inner = function (s) {
inner = s; };
return instance; })();
someObj.get_inner();//some value
someObj.set_inner("kkkk");
someObj.get_inner();//kkk
someObj.foo;//blah
someObj.foo="ddd";
someObj.foo;//ddd
non-module:
var someObj = function () {
var instance = {},
inner = 'some value';
instance.foo = 'blah';
instance.get_inner = function () {
return inner; };
instance.set_inner = function (s) {
inner = s; };
return instance; };
someObj().get_inner();//some value
someObj().foo;//blah
someObj.foo="aaa";
someObj().foo;//blah
someObj().set_inner("kkk");
someObj().get_inner();//some value
Any help is much appreciated. 任何帮助深表感谢。 Thanks!
谢谢!
Your "module" example creates a single object, referred to by instance
. 您的“模块”示例创建一个由
instance
引用的对象。 The anonymous function is immediately invoked, and returns that object. 立即调用匿名函数,并返回该对象。 So
someObj
refers to instance
. 所以
someObj
指的是instance
。
Your "non-module" example creates a new object each time you invoke it. 您的“非模块”示例在每次调用时都会创建一个新对象。 The anonymous function is not immediately invoked.
不会立即调用匿名函数。 Instead, it has to be called every time you want to use it.
相反,每次要使用它时都必须调用它。
It would behave the same way if you assigned the return value to a variable and referred to that, instead of repeatedly invoking someObj
: 如果将返回值分配给变量并引用它,而不是重复调用
someObj
,它的行为方式会相同:
var obj = someObj();
obj.get_inner(); //some value
obj.foo; //blah
obj.foo="aaa";
obj.foo; //aaa
//etc...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.