7

I am having a problem understanding why the following does not work. I looked at the other suggested answers and none of them addresses this clearly in the context of a new class object.

Given the code below:

class Example1 {
 constructor(v1) {
 this.v1 = v1;
 }
 method1() {
 console.log("v1 value = ",this.v1)
 }
}
const example1 = new Example1("value1");
const alias1 = example1.method1;
example1.method1();
alias1();

When I call alias1(), why is this undefined?

asked Sep 30, 2019 at 18:22
2

2 Answers 2

5

Its because the context of this changes when you call the alias1 (method1) just as a regular function instead of calling it on object.

When you call it on the object then the context of this is that object and in your case that context is lost and is either undefined or it falls back to the context of the global object (window in browsers) depending on the strict mode

You can set the context for this inside the alias using bind method to any object or you can define it inside some other object and that use that object to call it.

class Example1 {
 constructor(v1) {
 this.v1 = v1;
 }
 method1() {
 console.log("v1 value = ", this.v1)
 }
}
const example1 = new Example1("value1");
example1.method1();
const alias = example1.method1;
const alias1 = alias.bind(example1);
alias1();
const example2 = {v1: 'foo', alias}
example2.alias();

answered Sep 30, 2019 at 18:27
Sign up to request clarification or add additional context in comments.

Comments

3

Because this refers to method1 which does not have a v1 ,

You can use bind in the constructor :

Bind creates a new function that will have this set to the first parameter passed to bind().

class Example1 {
 constructor(v1) {
 this.v1 = v1;
 this.method1 = this.method1.bind(this);
 }
 method1() {
 console.log("v1 value = ", this.v1)
 }
}
const example1 = new Example1("value1");
const alias1 = example1.method1;
example1.method1();
alias1();

answered Sep 30, 2019 at 18:35

1 Comment

Thank you. For the use case I asked this question for, this is my preferred solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.