JS闭包将对象实例作为接口返回

时间:2018-02-16 11:49:50

标签: javascript ecmascript-5

我有以下代码。

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;
}}

我想要完成的是以下内容。我想要一个不是单身的班级Test。然后在我的应用程序的其他一些地方,我需要有一个函数,可以返回每个脚本执行相同的实例。我想我可以使用闭包getTestObj

但是,当我尝试使用它时

getTestObj().funct_1();

我收到以下错误,说未找到funct_1()

在对象函数(){...}中找不到函数funct_1。

显然,我在这里犯了一些错误,但是我无法在网上找到任何可以帮助我的解决方案。非常感谢任何评论。

注意:我被迫使用ECMA5

2 个答案:

答案 0 :(得分:1)

testObj包含在function

所以,要么叫它

getTestObj()().funct_1(); //notice two ()()

getTestObj()的值保存在变量

var singleTon = getTestObj();
var testObj = singleTon();
testObj.funct_1();

或者,只需return testObj(如果不需要单一的话)

function getTestObj() 
{
   var testObj;
   if (!testObj) {
      testObj = new Test();
   }
   return testObj;
}

并将其作为

调用
getTestObj().funct_1(); //notice single ()

答案 1 :(得分:0)

getTestObj()返回一个函数,即:

function() {
return testObj;
}

所以你必须再次调用它getTestObj()(),这将返回Test对象,现在你可以访问它的属性了。

getTestObj()().funct_1();

OR

您可以将getTestObj函数更改为:

function getTestObj() {
  var testObj;
  if (!testObj) {
     testObj = new Test();
  }
  return (function() {
        return testObj;
  }());
 }