Ank*_*ara 2 javascript jquery angular2-services angular angular5
我有一个名为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
});
}
}
Run Code Online (Sandbox Code Playgroud)
这是因为您在回调中丢失了作用域。修改它以使用箭头功能,以便保持this
$('#cmg tbody').on('click', 'a.editor_edit', (e) => {
e.preventDefault();
this.title= false;
});
Run Code Online (Sandbox Code Playgroud)
在使用箭头函数之前,每个新函数都定义了自己的值(对于构造函数而言,是新对象,在严格模式函数调用中未定义,如果该函数被称为“对象方法”,则为基础对象,等等)。事实证明,使用面向对象的编程风格并不理想。
| 归档时间: |
|
| 查看次数: |
1178 次 |
| 最近记录: |