我如何从javascript中返回的对象引用私有方法

How can i reference a private method from returned object in javascript?

本文关键字:对象引用 有方法 返回 javascript      更新时间:2023-09-26

从javascript中返回的对象中引用私有方法的最佳方法是什么?我给您留下一些示例代码:

var HelloWorld = (function(){
    var hello = function(){
        console.log("hello")
    },
    return{
        addToList: function(){
            //how can i reference hello from here dynamically like:
                            //this["hello"] or this["hell" + "o"]
        }       
    }
})()

因为返回值仍然在闭包内,所以可以直接调用hello。所以:

hello();

要使其"动态",正如其他答案所建议的那样,您需要将hello保存为某些东西。如果您想将它附加到this而不是另一个对象,您只需要存储对this的引用,以便以后可以访问它。

var HelloWorld = (function(){
  var self = this;
  this.hello = function(){
    console.log("hello")
  };
  return {
    addToList: function(){
        self["hello"]();
    }       
  }
})();

hello()不是一个方法。它只是闭包中的一个函数。所以,你可以在addToList()方法中调用它。

如果你想让hello函数表现得像一个将this设置为对象实例的方法,你必须像这个例子一样将实例传递给它。

var HelloWorld = (function(){
    var hello = function(){
        console.log("hello")
    },
    return{
        addToList: function(){
            //how can i reference hello from here dynamically like:
            hello.call(this);
        }       
    }
})()

如果你真正想做的是通过字符串引用访问hello函数,那么你就不能轻易地通过字符串名访问局部变量。如果想这样做,可以将hello函数放入一个局部对象中,如下所示:

var HelloWorld = (function(){
    var locals = {
        hello: function(){
            console.log("hello")
        }
    };
    return{
        addToList: function(){
            //how can i reference hello from here dynamically like:
            locals["hello"].call(this);
        }       
    }
})()

因此,您不能像示例代码注释中提到的那样"动态地"引用函数hello。(我假设你对"动态"的定义是给定一个包含单词"hello"的字符串,并以某种方式使用它来引用函数hello。)

但是,您可以将hello移动到对象中,并使用方括号符号从该对象中引用它:

var HelloWorld = (function () {
    var privateCode = {
        hello: function () {
            console.log('hello');
        }
    };
    return {
        addToList: function () {
            // access via `privateCode['hello']()`
        }       
    };
}());

你不能使用this,因为你没有使它成为对象的一部分。

var HelloWorld = (function () {
    var hello = function () { console.log("hello"); };
    return {
        addToList : function () { hello(); }
    };
}());

会很好。

如果您需要通过使用字符串访问它,那么您需要使hello,那么您有两个选项:

1)创建一个公共函数,你可以用一个字符串调用它,它调用hello

return {
    command : function (string) { if (this[string]) { this[string](); },
    sayHello : function () { hello(); }
};

2)创建一个私有对象,它存储你的方法(然后你可以用字符串调用它):

var private_actions = {
    hello : function () { console.log("hello"); }
};
return {
    command : function (string) {
        if (private_actions[string]) { private_actions[string](); }
    }
};

由于hello仅存在于匿名IIFE的作用域中,因此您需要将其存储在某个中间对象中,以便能够从公共方法动态访问hello:

var HelloWorld = (function(){
    var privates = {
        hello: function (){
            console.log("hello")
        }
    };
    return {
        addToList: function (){
            privates['hello']();
        } 
    }
})();
HelloWorld.addToList();
工作示例