无法从angular4中的嵌套函数访问它
Cannot Access this from nested function in angular4
我有一个名为 abc 的组件,在该组件中我有三个名为 title、Desc、Name 的变量,当我尝试从嵌套函数访问它时,它显示为未定义。
例如
@Component({
selector: 'abc',
templateUrl: './abc.component.html',
styleUrls: ['./abc.component.css'],
providers: [abcService]
})
export class abcComponent implements AfterViewInit,AfterViewChecked {
title;
Desc;
Name;
date=null;
test(){
this.title='a';
//work fine
}
test11(){
$('#cmg tbody').on('click', 'a.editor_edit', function (e) {
e.preventDefault();
this.title= false; //gives me an undefined
});
}
}
这是因为您在回调中丢失了范围。修改它以使用 arrow function 以便您保留 this
$('#cmg tbody').on('click', 'a.editor_edit', (e) => {
e.preventDefault();
this.title= false;
});
Until arrow functions, every new function defined its own this value
(a new object in the case of a constructor, undefined in strict mode
function calls, the base object if the function is called as an
"object method", etc.). This proved to be less than ideal with an
object-oriented style of programming.
我有一个名为 abc 的组件,在该组件中我有三个名为 title、Desc、Name 的变量,当我尝试从嵌套函数访问它时,它显示为未定义。
例如
@Component({
selector: 'abc',
templateUrl: './abc.component.html',
styleUrls: ['./abc.component.css'],
providers: [abcService]
})
export class abcComponent implements AfterViewInit,AfterViewChecked {
title;
Desc;
Name;
date=null;
test(){
this.title='a';
//work fine
}
test11(){
$('#cmg tbody').on('click', 'a.editor_edit', function (e) {
e.preventDefault();
this.title= false; //gives me an undefined
});
}
}
这是因为您在回调中丢失了范围。修改它以使用 arrow function 以便您保留 this
$('#cmg tbody').on('click', 'a.editor_edit', (e) => {
e.preventDefault();
this.title= false;
});
Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.