最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 2 "this" unable to access global variable in nested function - Stack Overflow

programmeradmin2浏览0评论

I'm quite new to Angular 2. Would like to ask how can I access "task_title" in the startTimer(). All I got from the console.log() is undefined. I believe the "this" was pointing to the function itself so I couldn't get the value of "task_title".

Is there anyway I can access to global variable in Typescript in a nested function?

export class DashboardComponent {

    task_title: string;

    myTimer = setTimeout(this.startTimer, 2000);

    updateTask(event: any){
        clearTimeout(this.myTimer);
        this.task_title = event.target.value;
        this.myTimer = setTimeout(this.startTimer, 2000);
    }

    startTimer() {
        console.log(this.task_title);
        this.myTimer = setTimeout(this.startTimer, 2000);
    };
}

Result: Undefined.

I'm quite new to Angular 2. Would like to ask how can I access "task_title" in the startTimer(). All I got from the console.log() is undefined. I believe the "this" was pointing to the function itself so I couldn't get the value of "task_title".

Is there anyway I can access to global variable in Typescript in a nested function?

export class DashboardComponent {

    task_title: string;

    myTimer = setTimeout(this.startTimer, 2000);

    updateTask(event: any){
        clearTimeout(this.myTimer);
        this.task_title = event.target.value;
        this.myTimer = setTimeout(this.startTimer, 2000);
    }

    startTimer() {
        console.log(this.task_title);
        this.myTimer = setTimeout(this.startTimer, 2000);
    };
}

Result: Undefined.

Share Improve this question asked Aug 4, 2016 at 8:15 DanzeeeeeDanzeeeee 2,6302 gold badges18 silver badges18 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 16

Use arrow functions or .bind(this) to retain the scope of this

myTimer = setTimeout(this.startTimer.bind(this), 2000);
myTimer = setTimeout(() => this.startTimer(), 2000);

Use reference for this like var self=this

export class DashboardComponent {

var self=this;


task_title: string;

myTimer = setTimeout(self.startTimer, 2000);

updateTask(event: any){
    clearTimeout(self.myTimer);
    self.task_title = event.target.value;
    self.myTimer = setTimeout(self.startTimer, 2000);
}

startTimer() {
    console.log(self.task_title);
    self.myTimer = setTimeout(self.startTimer, 2000);
};
}

Use call or apply

myTimer = setTimeout(this.startTimer.call(this), 2000);
myTimer = setTimeout(this.startTimer.apply(this), 2000);
发布评论

评论列表(0)

  1. 暂无评论