w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to access parent object's other properties without accessing parent reference directly in JavaScript?

No, there is not.

There is a composition relation. If you want to access the 'parent' you have to pass a reference explicitly. That's practice.

Now a word about "why":

A 'sub object' can be a sub-object of multiple objects:

var parent = new Parent;
var o = parent.bar;
o.bar.callFoosMethod(); // but o doesn't have a foo

This also creates issues with architecture. Circular structures are generally bad and the way objects communicate has to be as straightforward as possible.

If they need to talk it has to be through the parent, the Bar is not even aware of the fact there is a Foo there.

Workarounds


Although this is bad practice (high coupling, wrong place for responsibility, etc) if you must you can do:

function Parent() {
  this.foo = new Foo(this);
  this.bar = new Bar(this);
}

function Foo (parent) {
  this.sayHi = function () {
    console.log('Hello World');
  }
}

function Bar(parent) {
  this.callFoosMethod = function () {
       parent.foo.sayHi(); // BAD DESIGN WARNING!
  }
}

Again, this is really bad design. It completely violates the single responsibility principle, separation of concerns and clear communication. It generally indicates a design problem. Avoid it unless you're absolutely sure it's what you need.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.