JavascriptLoser
JavascriptLoser

Reputation: 1962

How to maintain original scope of 'this' when passing a function around?

I have a function, call it meow(), as part of a class, call it Cat:

export class Cat(){

    private meow(){
        console.log(this);
    }

Now, say I have another class, call it Kitten, which takes a function as part of its constructor:

export class Kitten {

    var kittenMeow: { (): void; }; //note the typing

    constructor(functionForMeow : { (): void; }){ //note the typing
        this.kittenMeow = functionForMeow;
    }

    public meow(){
        this.kittenMeow();
    }
}

Now say I add the following to the Cat class:

export class Cat(){

    constructor(){
        this.giveBirth();
    }

    private meow(){
        console.log(this);
    }

    giveBirth(){
        var kitty = new Kitten(this.meow);
        kitty.meow();
    }
}

When I run this code, "Kitten" is logged to the console. How can I make it so that "Cat" is logged to the console? That is, how do I preserve the original scope of this so that this refers to Cat and not Kitten

Upvotes: 2

Views: 51

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241208

You could use the .bind() method in order to specify the value of this in the current scope. Then when the function is executed, this will refer to Cat rather than Kitten.

var kitty = new Kitten(this.meow.bind(this));

In other words, since this refers to Cat within the giveBirth method context, that is the value that is passed when executing the function in the other scope.

export class Cat {
  giveBirth() {
    var kitty = new Kitten(this.meow.bind(this));
    kitty.meow();
  }
}

Upvotes: 1

Related Questions