从原型调用私有 js 函数

Calling private js function from prototype

本文关键字:js 函数 原型 调用      更新时间:2023-09-26

我整天都在阅读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_amember_b都已正确初始化。在我的页面调用中发生了其他一些魔术之后 MyObject.PublicFunction1(); ,ajax 执行,我输入operation1()operation2()但是当我进入这些member_amember_bundefined,我不明白为什么。我正在失去范围或其他东西。我在对象主体声明之外有私有函数和原型,两者的组合。如何从对象的原型调用私有函数来处理对象的数据?

我也试过

ClassBody{
vars
private function
}
prototype{
private function call
}

并一直在阅读此内容

operation1operation2没有上下文,因此在全局context中执行(其中this == window)。

如果要为它们提供上下文,但要保持它们的私密性,请使用 apply:

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

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

编辑

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

//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;
}());

我构建了一个工具,允许您将私有方法放到原型链上。这样,您将在创建多个实例时节省内存分配。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