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]();
}
};
}());
关于javascript - 内部对象如何在声明时引用其父对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35420631/