【问题标题】:How to maintain original scope of 'this' when passing a function around?传递函数时如何保持“this”的原始范围?
【发布时间】:2017-01-31 03:10:56
【问题描述】:

我有一个函数,叫它meow(),作为类的一部分,叫它Cat

export class Cat(){

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

现在,假设我有另一个类,称之为Kitten,它将一个函数作为其构造函数的一部分:

export class Kitten {

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

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

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

现在假设我将以下内容添加到 Cat 类中:

export class Cat(){

    constructor(){
        this.giveBirth();
    }

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

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

当我运行此代码时,“Kitten”会记录到控制台。我怎样才能使“猫”记录到控制台?也就是说,我如何保留this的原始范围,以便this引用Cat而不是Kitten

【问题讨论】:

    标签: javascript typescript this


    【解决方案1】:

    您可以使用.bind() method 在当前范围内指定this 的值。那么当函数执行时,this 将引用Cat 而不是Kitten

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

    换句话说,由于thisgiveBirth 方法上下文中引用Cat,所以这是在另一个范围内执行函数时传递的值。

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 2019-11-01
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2021-06-10
    相关资源
    最近更新 更多