代码之家  ›  专栏  ›  技术社区  ›  Todd Davis

Typescript、JQuery、Angular和“this”范围

  •  0
  • Todd Davis  · 技术社区  · 7 年前

    在Typescript中,“this”有时会变得有点模棱两可。通常,我能做的就是在绑定this时从另一个函数调用一个函数。

    this.myFunction.bind(this);
    

    这样,当myFunction()调用 this.whatever() ,它知道这是什么。

    getSlice(val): TimeSlice {
        const data = val.split(' ');
        const slice = new TimeSlice(val[0], val[1], val[2]);
        return slice;
    }
    
    ngAfterViewInit(): void {
        let current: TimeSlice = new TimeSlice();
        $('#selectable').selectable({
            stop: function() {
                const result = $('#select-result').empty();
                $('li.ui-selected', this).each(function() {
                    const val = $(this).attr('value');
                    current = this.getSlice(val); <!-- Here is the problem child -->
                });
            }
        });
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Sunil Singh    7 年前

    你可以保留 this 上下文。所以以后可以在嵌套函数中使用它。

    getSlice(val): TimeSlice {
        const data = val.split(' ');
        const slice = new TimeSlice(val[0], val[1], val[2]);
        return slice;
    }
    
    ngAfterViewInit(): void {
        let self =  this; //<-- keep `the` reference of Component
        let current: TimeSlice = new TimeSlice();
        $('#selectable').selectable({
            stop: function() {
                const result = $('#select-result').empty();
                $('li.ui-selected', this).each(function() {
                    const val = $(this).attr('value');
                    current = self.getSlice(val); <!-- Use self here -->
                });
            }
        });
    }
    
        2
  •  3
  •   Frank Modica    7 年前

    为了安全起见,可以事先创建函数:

    ngAfterViewInit(): void {
        let getSlice = val => this.getSlice(val);
    
        // Or do this
        // let getSlice = this.getSlice.bind(this);
    
        $('#selectable').selectable({
            stop: function() {
                const result = $('#select-result').empty();
                $('li.ui-selected', this).each(function() {
                    const val = $(this).attr('value');
                    current = getSlice(val);
                });
            }
        });
    }
    
    推荐文章