JavaScript: How to reference the top/root of a Class?

Viewed 113

So I have this problem:

class ClassName {
    constructor(value) {
        this.value = value;
    }
    someObject = {
        someFunction() {
            console.log(this.value);
        }
    }
}

The this.value of someFunction() doesnt reference the value defined within the constructor, it is because someFunction() is part of the someObject Object and this references the Object. So how can I reference the top/root of the Class within Objects/Properties of it to access values and properties there? I can also work with each Function being at the top level, but grouping them is way clearer.

2 Answers

You can use an arrow-function in order not to create a new scope:

class ClassName {
  constructor(value) { this.value = value; }
  someObject = {
    someFunction: () => { console.log(this.value); }
  }
}

const obj = new ClassName(1);

obj.someObject.someFunction();

If you want to use a normal function, you need to use bind:

class ClassName {
  constructor(value) { this.value = value; }
  someObject = {
    someFunction() { console.log(this.value); }
  }
}

const obj = new ClassName(1);

const fn = obj.someObject.someFunction.bind(obj);

fn();

Just write the function as arrow function like this to bind this at declaration time. As you can see in the example below, this syntax implies that someObject is being instantiated once per object instance, so you're not leveraging JavaScript's prototypal inheritance which is less good in terms of memory consumption.

class ClassName {
    constructor(value) {
        this.value = value;
    }
    someObject = {
        someFunction: () => console.log(this.value)
    }
}

const obj = new ClassName('test');

obj.someObject.someFunction();

const obj2 = new ClassName;

console.log(obj2.someObject === obj.someObject); // false

Related