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();

1

2 Answers 2

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();

Sign up to request clarification or add additional context in comments.

Comments

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>

2 Comments

Yes!, I didn't know about I can reference the object in let, Thanks!.
Sorry, It worked, but the Barmar's answer is cleaner. If I had the priviledge to give upvote I would have given you one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.