如何创建公共和私人会员? [英] How to create public and private members?

查看:134
本文介绍了如何创建公共和私人会员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑,我怎样才能创建公共和私人会员。

I'm a bit confused, how can I create public and private members.

到目前为止,我的代码模板如下:

My code template so far is like:

(function()){
   var _blah = 1;

   someFunction = function() {
     alert(_blah);
   };

   someOtherFunction = function() {
     someFunction();
   }
}();


推荐答案

您可能想要使用 Yahoo Module Pattern

myModule = function () {

    //"private" variables:
    var myPrivateVar = "I can be accessed only from within myModule."

    //"private" method:
    var myPrivateMethod = function () {
        console.log("I can be accessed only from within myModule");
    }

    return {
        myPublicProperty: "I'm accessible as myModule.myPublicProperty."

        myPublicMethod: function () {
            console.log("I'm accessible as myModule.myPublicMethod.");

            //Within myProject, I can access "private" vars and methods:
            console.log(myPrivateVar);
            console.log(myPrivateMethod());
        }
    };
}();

您定义的私人会员 myPrivateVar myPrivateMethod 已定义,您的公共成员 myPublicProperty myPublicMethod 已定义。

You define your private members where myPrivateVar and myPrivateMethod are defined, and your public members where myPublicProperty and myPublicMethod are defined.

您可以按如下方式访问公共方法和属性:

You can simply access the public methods and properties as follows:

myModule.myPublicMethod();    // Works
myModule.myPublicProperty;    // Works
myModule.myPrivateMethod();   // Doesn't work - private
myModule.myPrivateVar;        // Doesn't work - private

这篇关于如何创建公共和私人会员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆