简体   繁体   English

在嵌套对象中访问parent的属性

[英]Accessing property of parent in nested object

I am refactoring some JS code and need to access Objects like 我正在重构一些JS代码,需要访问像

Object1.Object2.IsValid();

this is what I have right now. 这就是我现在所拥有的。

function _Object1(object) {

    this._object1 = object;

    this.Object2= new _Object2();

    function IsValid() {
        // tests here
    }
}

function _Object2()
{
    function IsValid() {
        // tests here but needs to use Object1 property above.
    }
}

Only problem being, I am not sure how to access Object1 in Object2 without passing any parameter. 唯一的问题是,我不知道如何在不传递任何参数的情况下访问Object2中的Object1。 Nesting Object2 in Object1, perhaps? 或许在Object1中嵌套Object2?

Edit: I am tring to implement OOP in JS, which is like reinventing the wheel, but want to try it for now :) 编辑:我想在JS中实现OOP,就像重新发明轮子一样,但是现在想尝试一下:)

I will explain the question in terms of OOP: 我将用OOP来解释这个问题:

I have a class _Object1 and it has a method IsValid() . 我有一个类_Object1 ,它有一个方法IsValid() _Object1 also has a property Object2 which is of type _Object2 . _Object1还有一个属性Object2 ,其类型为_Object2

Now, _Object2 also has method named IsValid() . 现在, _Object2还有一个名为IsValid()方法。 But here is a catch, _Object2.IsValid need the value of _Object1 for tests. 但是这里有一个catch, _Object2.IsValid需要_Object2.IsValid的值_Object1进行测试。

For the above code if I do: 对于上面的代码,如果我这样做:

var Object1 = new _Object1();

I can simply call Object1.Object2.IsValid() for the result. 我可以简单地为结果调用Object1.Object2.IsValid() Isn't it? 不是吗?

Disclaimer: I have been using JS for sometime now, but never had to dabble with things like these. 免责声明:我现在一直在使用JS,但从来不必涉及这些事情。

Give _Object2 what it needs: _Object2它需要的东西:

function _Object1(object) {

    this._object1 = object;

    this.Object2= new _Object2(this);

    function IsValid() {
        // tests here
    }
}

function _Object2(parentObject)
{
    function IsValid() {
        // parentObject refers to the _Object1 that created this object
    }
}

I think what you're looking for is impossible, unless you are willing to pass the data in to the object. 我认为你要找的东西是不可能的,除非你愿意将数据传递给对象。

Just because your _Object2 instance has been created inside the _Object1 constructor, it does not automatically have any reference to the data of your _Object1 instance. 只是因为_Object2实例是在_Object1构造函数中创建的,它不会自动引用_Object1实例的数据。 You would have to tell the _Object2 instance about the _Object1 values either in the constructor function or via some other method: 您必须在构造函数或通过其他方法告诉_Object2实例有关_Object1值:

function _Object2(parentObject) { /* ... */ }
// or
_Object2.prototype.setParent = function(parent) { /* ... */}
// or
myObject2.parent = this._object1;

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

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