内部对象如何在声明时引用其父对象的对象

How can an inner object reference its parent's objects at declaration?

本文关键字:对象 引用 声明 内部对象      更新时间:2023-09-26

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对象内部,但这需要对我正在处理的实际代码进行一些重构,我只想让它工作(。

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

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/

你可以简单地重组一下,并使用"bind"将对象构造函数中的"this"绑定到应该引用它的函数。

function someObject() {
  this.methods = {
    method1: function() {
      console.log(this);
      console.log("method 1");
    },
    method2: this.method2.bind(this)
  }
}
someObject.prototype.run = function(str) {
  console.log("running");
  this.methods[str]();
}
someObject.prototype.method2 = function() {
  console.log(this);
  console.log("method 2");
}
var a = new someObject();
a.run("method1");
a.run("method2");

我不

认为这是否正是您要找的,但我发现您可以使用getters来实现它。

例如:

var test = {
  someProperty: true,
  get somePropertyReference() {
    return this.someProperty;
  }
};
console.log(test.somePropertyReference);