JS 闭包 return 对象实例作为接口
JS closure to return object instance as interface
我有以下代码。
function Test() {
this.funct_1 = function() {
alert('funct_1');
}
this.funct_2 = function() {
alert('funct_2');
}
return this;}
function getTestObj() {
var testObj;
if (!testObj) {
testObj = new Test();
}
return function() {
return testObj;
}}
我想要完成的是以下内容。我想要一个 class Test
不是单例的。然后在我的应用程序的其他一些地方,我需要有一个函数可以 return 每个脚本执行相同的实例。我认为我可以为此使用闭包 getTestObj
。
然而,当我尝试使用它时
getTestObj().funct_1();
我收到以下错误,提示未找到 funct_1()
。
在对象函数 () {...} 中找不到函数 funct_1。
显然,我在这里犯了某种错误,但我无法在网上找到任何可以帮助我的解决方案。不胜感激。
注意:我不得不使用 ECMA5
testObj
包裹在 function
中
所以,要么叫它
getTestObj()().funct_1(); //notice two ()()
将getTestObj()
的值保存在变量
中
var singleTon = getTestObj();
var testObj = singleTon();
testObj.funct_1();
或者,简单地 return testObj
(如果不需要 singleTon)
function getTestObj()
{
var testObj;
if (!testObj) {
testObj = new Test();
}
return testObj;
}
并将其调用为
getTestObj().funct_1(); //notice single ()
getTestObj() 是 returning 一个函数,即:
function() {
return testObj;
}
因此您必须再次调用它 getTestObj()(),这将 return 测试对象,现在您可以访问它的属性。
getTestObj()().funct_1();
或
您可以将 getTestObj 函数更改为:
function getTestObj() {
var testObj;
if (!testObj) {
testObj = new Test();
}
return (function() {
return testObj;
}());
}
我有以下代码。
function Test() {
this.funct_1 = function() {
alert('funct_1');
}
this.funct_2 = function() {
alert('funct_2');
}
return this;}
function getTestObj() {
var testObj;
if (!testObj) {
testObj = new Test();
}
return function() {
return testObj;
}}
我想要完成的是以下内容。我想要一个 class Test
不是单例的。然后在我的应用程序的其他一些地方,我需要有一个函数可以 return 每个脚本执行相同的实例。我认为我可以为此使用闭包 getTestObj
。
然而,当我尝试使用它时
getTestObj().funct_1();
我收到以下错误,提示未找到 funct_1()
。
在对象函数 () {...} 中找不到函数 funct_1。
显然,我在这里犯了某种错误,但我无法在网上找到任何可以帮助我的解决方案。不胜感激。
注意:我不得不使用 ECMA5
testObj
包裹在 function
所以,要么叫它
getTestObj()().funct_1(); //notice two ()()
将getTestObj()
的值保存在变量
var singleTon = getTestObj();
var testObj = singleTon();
testObj.funct_1();
或者,简单地 return testObj
(如果不需要 singleTon)
function getTestObj()
{
var testObj;
if (!testObj) {
testObj = new Test();
}
return testObj;
}
并将其调用为
getTestObj().funct_1(); //notice single ()
getTestObj() 是 returning 一个函数,即:
function() {
return testObj;
}
因此您必须再次调用它 getTestObj()(),这将 return 测试对象,现在您可以访问它的属性。
getTestObj()().funct_1();
或
您可以将 getTestObj 函数更改为:
function getTestObj() {
var testObj;
if (!testObj) {
testObj = new Test();
}
return (function() {
return testObj;
}());
}