如何从以下代码中的bar()函数内部访问baz()?
var obj = {
baz : function(){ alert("Hi!"); },
foo: {
bar: function(){
baz();
}
}
}
答案 0 :(得分:3)
JavaScript并没有内置的父引用,因为多个父母可以引用一个对象'我们称之为多对一关系。
正如其他人所说,在这个简化的案例中,只需调用obj.baz()
即可。
在更复杂的情况下,您必须手动构建对象并跟踪父母身份:
// Create the root object
var rootObject = {baz: function() {console.log('rootBaz');}}
// And the basic child
var childObject = {foo: function() {console.log('childFoo');}}
// Configure the parent
childObject.parent = rootObject;
// Add our call.
childObject.baz = function() {this.parent.baz()};
// Invoke and test
childObject.baz();
可以略微简化:
var rootObject = {
baz: function() {console.log('rootBaz');}
};
var childObject = {
foo: function() {console.log('childFoo');},
baz: function() {this.parent.baz()}
};
childObject.parent = rootObject;
childObject.baz();
根据Sujet的评论更新
此外,如果您需要确保baz
具有this
的正确值,则可以使用call
或apply
。
baz: function() {this.parent.baz.call(this.parent)}
如果您的代码不需要this
,那么我会根据原始答案推荐直接函数调用。
答案 1 :(得分:1)
只需使用对象引用:
var obj = {
baz : function(){ alert("Hi!"); },
foo: {
bar: function(){
obj.baz();
}
}
}
答案 2 :(得分:0)
您需要通过object.property表示法引用。
在你的例子中,你会得到baz via:
obj.baz()
一些很好的资源: