相关疑难解决方法(0)

Javascript在同一个对象中从私有方法调用公共方法

我可以在私人方式中调用公共方法:

var myObject = function() {
   var p = 'private var';
   function private_method1() {
      //  can I call public method "public_method1" from this(private_method1) one and if yes HOW?
   }

   return {
      public_method1: function() {
         // do stuff here
      }
   };
} ();
Run Code Online (Sandbox Code Playgroud)

javascript oop

12
推荐指数
2
解决办法
1万
查看次数

在使用javascript模块模式时,如何从私有方法中调用公共方法?

我想从私有方法调用公共方法,但属性"this"指向窗口对象.

请注意我正在尝试应用模块模式.您可以在jsfiddle.net上找到一个有效的代码示例

// how can i access a public method from a private one?
// (in this example publicAlert from privateMethod)
// this refers to the window object.

$(function() {
var modulePattern = (function($)
{
    var privateMethod = function()
    {
        appendText("called privateMethod()");
        this.publicAlert();
    };

    var appendText = function(texToAppend)
    {
        var text = $('#output').text() + " | " + texToAppend;
        $('#output').text(text);
    };

    return {
        publicMethod : function()
        {
            appendText("called publicMethod()");
            privateMethod();
        },

        publicAlert : function()
        {
            alert("publicAlert");
        }
    }; …
Run Code Online (Sandbox Code Playgroud)

javascript module-pattern

9
推荐指数
1
解决办法
2168
查看次数

标签 统计

javascript ×2

module-pattern ×1

oop ×1