简体   繁体   English

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

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

Which is the best way to reference a private method from returned object in javascript? 从javascript中返回的对象引用私有方法的最佳方法是什么? I leave you some sample code: 我给你一些示例代码:

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"]
        }       
    }
})()

Because the return is still inside the closure, you can just call hello directly. 由于返回值仍在闭包内部,因此您可以直接调用hello So: 所以:

hello();

To make it "dynamic", as the other answers recommend, you need to save hello to something. 如其他答案所建议,要使其“动态”,您需要保存hello If you want to attach it to this instead of another object, you just need to store off a reference to this so you can access it later. 如果要将其附加this对象而不是其他对象,则只需存储this的引用,以便以后可以访问它。

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

hello() is not a method. hello()不是方法。 It's just a function in a closure. 它只是一个闭包中的函数。 So, you can just call it from within your addToList() method. 因此,您可以从addToList()方法中调用它。

If you want the hello function to behave like a method with this set to the object instance, you'd have to pass the instance to it as in this example. 如果你想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);
        }       
    }
})()

If what you're really trying to do is to access the hello function by a string reference, you cannot easily access local variables by string name. 如果您真正想做的是通过字符串引用访问hello函数,则无法轻易通过字符串名称访问局部变量。 If you wanted to do that, you could have to put the hello function into a local object like this: 如果要这样做,则可能必须将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);
        }       
    }
})()

As is, you cannot reference the function hello "dynamically" as mentioned in the comment of your sample code. hello原样,您不能像示例代码的注释中所提到的那样“动态地”引用函数hello (I am assuming your definition of "dynamically" is to be given a string containing the word "hello" and somehow use it to reference the function hello .) (我假设将为您“动态地”定义一个包含单词“ hello”的字符串,并以某种方式使用它来引用函数hello 。)

You could, however, move hello into an object and reference it off that object using square bracket notation: 但是,您可以将问候移动到对象中,并使用方括号表示法将其引用到该对象之外:

var HelloWorld = (function () {
    var privateCode = {
        hello: function () {
            console.log('hello');
        }
    };

    return {
        addToList: function () {
            // access via `privateCode['hello']()`
        }       
    };
}());

You can't use this , because you haven't made it a part of the object. 您不能使用this ,因为还没有使其成为对象的一部分。

var HelloWorld = (function () {

    var hello = function () { console.log("hello"); };

    return {
        addToList : function () { hello(); }
    };

}());

That will work fine. 那会很好的。

If you need to access it by using a string, then you need to make hello , then you have two options: 如果需要使用字符串访问它,则需要打个hello ,然后有两个选择:

1) make a public function, which you CAN call with a string, which calls hello 1)设置一个公共函数,您可以使用字符串来调用它,它调用hello

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

2) make a private object, which stores your methods (then you can call it with a string): 2)创建一个私有对象,该对象存储您的方法(然后您可以使用字符串来调用它):

var private_actions = {
    hello : function () { console.log("hello"); }
};

return {
    command : function (string) {
        if (private_actions[string]) { private_actions[string](); }
    }
};

Since hello only exists in the scope of an anonymous IIFE, you'd need to store it some intermediate object in order to be able to dynamically access hello from a public method: 由于hello仅存在于匿名IIFE的范围内,因此您需要将其存储一些中间对象,以便能够从公共方法动态访问hello

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

    return {
        addToList: function (){
            privates['hello']();
        } 
    }
})();

HelloWorld.addToList();

Working Example 工作实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从jQuery $ .get方法读取返回的对象 - how can I read returned object from jQuery $.get method 如何从 javascript 中的方法引用中检索 class? - How can I retrieve a class from a method reference in javascript? JavaScript - 如何/可以从函数中将对象引用设置为null? - JavaScript - How/Can I set an object reference to null from a function? 如何在Javascript中访问其他对象的私有方法(但它是同一个instanceof) - How Can I Access private method of other object (but it's same instanceof) in Javascript 如何在 HTML 中引用对象中的方法 - How can I reference an method in HTML that is in an object 如何从 object 外部(通过事件)引用 javascript 中的 object 方法? - How do I reference an object method in javascript from outside the object (through event)? 在使用javascript模块模式时,如何从私有方法中调用公共方法? - How can i call a public method from within a private one when using the javascript Module Pattern? 如何从javascript对象执行公共方法 - How can I execute public method from javascript object 如何在方法中更改JavaScript对象的状态? - How can I alter the state of a JavaScript object from within a method? 如何通过属性的 onclick 方法引用 javascript object? - How can I reference a javascript object through a property's onclick method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM