2

I have a function inside an object inside a Class.

The object of the class is initialized and I want to call the function, but the function need a variable defined on the constructor of the Class.

class someClass {
  constructor() {
    this.foo = "bar";

    this.print = {
      variable: function() {
        console.log(this.foo);
      }
    };

  }
}

// And I call it from the global scope

var someObject = new someClass();

someObject.print.variable();

It will print

undefined

I know is a different scope and maybe I can't access to it.

The objective of this is to have some order with my functions.

I want to access to my function like someObject.print.variable();

BlueSeph
  • 543
  • 1
  • 8
  • 25
  • 2
    Not exactly the same situation, but the exact same set of answers applies: https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – Ry- Mar 03 '18 at 00:19

2 Answers2

5

Use an arrow function, it will be bound to the original this in the object that defined it.

class someClass {
  constructor() {
    this.foo = "bar";

    this.print = {
      variable: () => {
        console.log(this.foo);
      }
    };

  }
}

// And I call it from the global scope

var someObject = new someClass();

someObject.print.variable();
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Something like this maybe?

<script>
class someClass {
  constructor() {
    let that = this;
    this.foo = "bar";

    this.print = {
     variable: function() {
        console.log(that.foo);
       }    
    };

  }
}

//And I call it from the global scope

var someObject = new someClass();

someObject.print.variable();
</script>
vityavv
  • 1,482
  • 12
  • 23