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

时间:2016-02-15 22:55:25

标签: javascript scope

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

methods

有没有办法让这项工作?

我可以将方法声明移到public class MainClass { public static void main(String[] args){ printAllSequences("GAAAAATTTTCCCCCACCCTTTTCCCC", 10); } public static void printAllSequences(String DNASequence, int subSequenceSize){ for(int i=0; i<DNASequence.length() - subSequenceSize - 1; i++){ System.out.println(DNASequence.substring(i, i + subSequenceSize)); } } } 对象中,但是这需要对我正在处理的实际代码进行一些重构,我只想让它工作起来) 。

3 个答案:

答案 0 :(得分:2)

如前所述,无法从对象文字中的嵌套对象引用父属性 但我建议使用模块化模式进行替代。 以下方法使用单个公共方法someObject生成并返回对象run
“标记为私有对象的”主“对象,不能被某人修改或访问。 (现在很安全。)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/

答案 1 :(得分:0)

我不认为这究竟是你在寻找什么,但我发现你可以使用getters来实现它。

例如:

&#13;
&#13;
var test = {
  someProperty: true,
  get somePropertyReference() {
    return this.someProperty;
  }
};

console.log(test.somePropertyReference);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以通过简单地重构一下并使用&#34; bind&#34;绑定&#34;这个&#34;在对象构造函数中应该引用它的函数。

&#13;
&#13;
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");
&#13;
&#13;
&#13;

相关问题