javascript - 内部对象如何在声明时引用其父对象?

标签 javascript scope

JSFiddle:https://jsfiddle.net/dyncmuks/1/

var someObject = {

  run: function(str) {
    console.log("running");
    this.methods[str]();
  },

  method1: function() {

    console.log("method 1");
  },

  method2: function() {
    console.log("method 2");
  },


  methods: {

    one: this.method1,    //This == the 'methods' object
    two: this.method2     //I want to refer to the 'someObject' object

  }

};

有没有办法让它工作?

我可以将方法声明移动到 methods 对象内部,但这需要对我正在处理的实际代码进行一些重构,我只是想让它工作)。

最佳答案

如前所述,无法从对象字面量中的嵌套对象引用父属性。
但我会建议使用 模块化模式 的一些替代方案。 以下方法使用单个公共(public)方法 run 生成并返回对象 someObject
标记为私有(private)对象的“主”对象无法修改或可由某人访问。(现在安全了)。
getMethods 方法“隐式”返回“main”对象的所有方法的列表(对象)。

var someObject = (function(){

  var privateObj = {
      method1: function() {
        console.log("method 1");
      },
      method2: function() {
        console.log("method 2");
      },
      method3: function() {
        console.log("method 3");
      },
      getMethods : function(){
        var self = this;
        return {
            one: self.method1,
            two: self.method2,
            three: self.method3
        };
      }
  };

  return {
      run: function(str) {
          console.log("running");
          privateObj.getMethods()[str]();
      }
  };

}());

https://jsfiddle.net/xnbe510b/

关于javascript - 内部对象如何在声明时引用其父对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35420631/

相关文章:

javascript - 将新的变量作用域应用于对象

javascript - react : Are keys useful for any situations other than lists?

javascript - onclick=GA 代码给出服务器错误 500

sql - 计数子项的范围 has_many 关系

R Shiny : "global" variable for all functions in server. R

c++ - 如何引用与 C++ 中的局部变量同名的全局变量?

java - 错误 : 'else' without 'if'

javascript - 我需要能够按下一个按钮来推特报价

javascript - 如何在输入类型 Number 中屏蔽 +、-、e?

javascript - 如何在容器中保持动画div