简体   繁体   中英

javascript this is undefined in a method

I want to add a value to an array, by parsing a method from a class to a function.

Example

The Class:

class Foo {
    constructor() {
        this.arr = [];
    }

    add(value) {
        this.arr.push(value);
    }
}

Usage:

let foo = new Foo();
a(foo.add, "a String");

function a(func, value) {
    func(value);
}

Your add function isn't bound to your object, which means that the this variable depends on the context it is.

If you do

constructor() {
    this.arr = [];
    this.add = this.add.bind(this);
}

It will replace the add that is not bound to the new one that wherever you call it, it will reference this instance.

Or in ES6 you can do, which makes the same bind as my previous example but under the hood.

add = (value) => {
    this.arr.push(value);
}

In the constructor you need to bind the add function to that class.

this.add = this.add.bind(this);

Also you need to refer to arr variable with this. this.arr.push

Which keeps the context of that instance of Foo.

Use arrow function to prevent auto bind add = (value) => {...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM