1

我整天都在阅读 SO 帖子,但我没有想出任何对我有用的东西。

我有一个 JS 对象

function MyObject(a,b){
     this.member_a = a;
     this.member_b = b;



     function operation1(){
          $('#someDiv1').text(this.a);
     }

     function operation2(){
          $('#someDiv1').text(this.b);
     }

     MyObject.prototype.PublicFunction1 = function(){

     //There is an ajax call here
     //success
     operation1();
     //failure
     operation2();

     }
}

大致就是这样。这就是我现在的模式。它在一个外部 JS 文件中。我的页面创建了一个MyObject(a,b),断点显示member_a并且member_b都正确初始化。在我的页面调用发生其他一些魔术之后MyObject.PublicFunction1();,ajax 执行并且我进入operation1()或者operation2()但是当我在其中member_a并且member_b两者都是undefined并且我不明白为什么。我失去了范围或其他东西。我有对象主体声明之外的私有函数和原型,两者的组合。如何从对象的原型中调用私有函数来处理对象的数据?

我也试过

ClassBody{
vars
private function
}

prototype{
private function call
}

并且一直在读这个

4

2 回答 2

1

operation1并且operation2没有上下文,因此在全局context(where this == window)中执行。

如果你想给他们一个上下文,但让他们保密,那么使用 apply:

operation1.apply(this);
operation2.apply(this);

进一步阅读 apply 方法https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

编辑

@FelixKing 是正确的-您的代码应该更适合这样编写(使用Module Pattern):

//encapsulating scope
var MyObject = (function() {

     function operation1(){
          $('#someDiv1').text(this.a);
     }

     function operation2(){
          $('#someDiv1').text(this.b);
     }

     var MyObject = function(a,b) {
        this.member_a = a;
        this.member_b = b;
     };

     MyObject.prototype.PublicFunction1 = function(){

     //There is an ajax call here
     //success
     operation1.apply(this);
     //failure
     operation2.apply(this);

     }

     return MyObject;
}());
于 2013-09-24T13:11:52.240 回答
0

我已经构建了一个工具,允许您将私有方法放到原型链上。这样,您将在创建多个实例时节省内存分配。 https://github.com/TremayneChrist/ProtectJS

例子:

var MyObject = (function () {

  // Create the object
  function MyObject() {}

  // Add methods to the prototype
  MyObject.prototype = {

    // This is our public method
    public: function () {
      console.log('PUBLIC method has been called');
    },

    // This is our private method, using (_)
    _private: function () {
      console.log('PRIVATE method has been called');
    }
  }

  return protect(MyObject);

})();

// Create an instance of the object
var mo = new MyObject();

// Call its methods
mo.public(); // Pass
mo._private(); // Fail
于 2014-01-16T16:42:43.427 回答