var foo={} Foo.method = function () { var i = 0; return { a:function () { console.log (' AA ', i++); }, b:function () { console.log (' BB ', i++); } } } Foo.method (). A (); Foo.method (). b ();
var bar= (function () { var instance; function init () { var i =0; return { a:function () { console.log (' cc ', i++); }, b:function () { console.log (' ee ', i++); } } } return { method:function () { if (!instance) { instance = init () } return instance; } } }()); Bar.method (). A (); Bar.method (). b ();
In the first way, two calls method()
re-created the returned object, re-initialized each time the object was created, i
so it is called a()
and b()
has no relationship, and there is no continuity.
The second way is equivalent to the execution of the results 缓存
, the advantage is to cache the benefits (faster reading again), the downside is the downside of the cache (Resource/memory more, longer).
var foo={} Foo.method = function () {var i = 0; return {a:function () {console.log (' AA ', i++); }, B:function () {console.log (' BB ', i++); }}} var foo = Foo.method (); FOO.A (); FOO.B (); var bar= (function () {var instance; function init () {var i = 0; return {a:function () {console.log (' cc ', i++); }, B:function () {console.log (' ee ', i++); }}} return {method:function () {if (!instance) {instance = init ()} return instance; } } }()); Bar.method (). a (); Bar.methOD (). b ();
Caching the results of the Foo.method () method through Foo all FOO.B () is modified on the result of FOO.A ()
Both of these ways can have the same result
What is the difference between Var foo= {}; Foo.method () and singleton mode