简体   繁体   English

从子Javascript访问父方法

[英]Access Parent method from child Javascript

How can I access baz() from inside the bar() function in the following code? 如何在以下代码的bar()函数内部访问baz()?

var obj = {
    baz : function(){ alert("Hi!"); },
    foo: {
        bar: function(){ 
            baz(); 
        }
    }
}

JavaScript doesn't have kind of a built-in parent reference because an object can be referenced by multiple 'parents' in what we call a many-to-one relationship. JavaScript没有内置的父引用,因为一个对象可以被我们称为多对一关系的多个“父”引用。

As others have said, in this simplified case, simply calling obj.baz() will work. 正如其他人所说,在这种简化的情况下,只需调用obj.baz()

In a more complicated case, you would have to manually build the object and track parenthood: 在更复杂的情况下,您将必须手动构建对象并跟踪父母身份:

// 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();

Which can be slightly simplified: 可以稍微简化一下:

var rootObject = {
  baz: function() {console.log('rootBaz');}
};

var childObject = {
  foo: function() {console.log('childFoo');},
  baz: function() {this.parent.baz()}
};

childObject.parent = rootObject;
childObject.baz();

Updated per Sujet's comment 根据Sujet的评论更新

In addition, if you need to make sure that baz has the correct value for this you can use either call or apply . 另外,如果您需要确保baz具有正确的值, this可以使用callapply

  baz: function() {this.parent.baz.call(this.parent)}

If your code doesn't require this then I would recommend a straight function call per my original answer. 如果你的代码不需要this ,那么我会建议每个我原来的答复直线函数调用。

Just use the object reference: 只需使用对象引用:

var obj = {
    baz : function(){ alert("Hi!"); },
    foo: {
        bar: function(){ 
            obj.baz(); 
        }
    }
}

You need to reference via object.property notation. 您需要通过object.property表示法进行引用。

In your example you would get baz via: 在您的示例中,您将通过以下方式获得baz:

obj.baz()

Some great resources for this : 一些很好的资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM