I am refactoring some JS code and need to access Objects like
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. Nesting Object2 in Object1, perhaps?
Edit: I am tring to implement OOP in JS, which is like reinventing the wheel, but want to try it for now :)
I will explain the question in terms of OOP:
I have a class _Object1
and it has a method IsValid()
. _Object1
also has a property Object2
which is of type _Object2
.
Now, _Object2
also has method named IsValid()
. But here is a catch, _Object2.IsValid
need the value of _Object1
for tests.
For the above code if I do:
var Object1 = new _Object1();
I can simply call Object1.Object2.IsValid()
for the result. Isn't it?
Disclaimer: I have been using JS for sometime now, but never had to dabble with things like these.
Give _Object2
what it needs:
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. You would have to tell the _Object2
instance about the _Object1
values either in the constructor function or via some other method:
function _Object2(parentObject) { /* ... */ }
// or
_Object2.prototype.setParent = function(parent) { /* ... */}
// or
myObject2.parent = this._object1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.