2016-02-15 102 views
1

的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對象中,但是這需要對我正在處理的實際代碼進行一些重構,而我只是想讓它工作)。

+5

沒有辦法從它的對象初始化內部表示一個對象的屬性。在初始化程序正在評估時,該對象並不存在。 – Pointy

+0

[你想要做什麼](http://meta.stackexchange.com/a/66378)? –

+0

@ Mike'Pomax'Kamermans - 我有一堆不同的'主要'方法的對象。我需要將它們放到key:values(key:functions)列表中,以便它們可以迭代以便從列表中進行選擇。 – dwjohnston

回答

2

正如所提到的,沒有辦法從嵌套對象參照父屬性在對象常量。
但我會建議一些替代與模塊化模式。 以下方法使用單個公共方法run生成並返回對象someObject
標記爲專用對象的「主」對象,它不能被修改或被某人訪問(現在是安全的)。
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/

0

我不認爲如果這正是你在找什麼,但我發現你可以使用getters來實現它。

例如:

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

 
console.log(test.somePropertyReference);

+0

只要您的支持是爲IE9 +;即使您使用替代方法(無語法更改)來定義它們,也無法在早期瀏覽器中使用backfill(polyfill)getter和setter。 – Norguard

0

,你可以通過簡單重組這一點,使用「綁定」綁定「這個」在對象構造函數應該有借鑑它的職能。

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");