简体   繁体   English

私有成员对象包含函数

[英]Private Member To Object Containing Function

In javascript, I have an object containing a function and want to add to it a private member. 在javascript中,我有一个包含函数的对象,并希望向其添加一个私有成员。 How can I do that? 我怎样才能做到这一点?

function function1 () {
    var function2 = function () {
        console.log("This is an actual function.");
    }

    function2.publicMember = 5;
    function2.privateMember = 7; 

    return function2;
}

I want privatMember to be inaccessible to the user of function1. 我希望function1的用户无法访问privatMember。 I found this question but I can't quite translate it to my situation because my object is a function: 我发现了这个问题,但我无法将其转换为我的情况,因为我的对象是一个函数:

How to add private variable to this Javascript object literal snippet? 如何将私有变量添加到此Javascript对象文字片段?

thanks! 谢谢!

Wrap it into one more function to create new scope (ie using iife ): 将其包装成另一个函数以创建新范围(即使用iife ):

function function1 () {
     var function2 = (function(){
       var privateMember = 7; 
       return function () {
          privateMember ++; // do something with really private member
          console.log("This is an actual function.");
       }
    })();

    function2.publicMember = 5;

    return function2;
}

Declare the vars inside the function that needs access to them: 在需要访问它们的函数内声明变量:

function function1 () {
    var publicMember = 5;
    var function2 = function () {
        var privateMember = 7;
        console.log("This is an actual function.");
    }

    return function2;
}

So function2 can see the vars inside its own closure (privateMember) and any parent scope. 因此,function2可以在其自己的闭包(privateMember)和任何父作用域内看到变量。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM