[英]How can i reference a private method from returned object in javascript?
从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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.