2

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.

  • You don't. That's why you don't use objects to group methods. (Though in your case they're not normal *methods* anyway, they're instantiated with every single instance - if you really want this, you might consider not using `class` syntax at all) – Bergi May 29 '21 at 20:55
  • Not using `class` syntax, but have a look at [these](https://stackoverflow.com/questions/15884096/organize-prototype-javascript-while-perserving-object-reference-and-inheritance) [old questions](https://stackoverflow.com/questions/16502467/prototype-deep-scope-of-this-to-access-instances-scope) – Bergi May 29 '21 at 20:57

2 Answers2

2

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();
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
2

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
Guerric P
  • 30,447
  • 6
  • 48
  • 86