I have a component called abc and in that component I have three variable named title,Desc,Name and when I am trying to access it from nested function it gives me as undefined.
我有一个名为abc的组件,在该组件中我有三个名为title,Desc,Name的变量,当我尝试从嵌套函数访问它时,它给我一个未定义的。
e.g.
例如
@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
});
}
}
1 个解决方案
#1
2
This is because you are losing the scope in your callback. Modify it to use an arrow function so that you keep 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.
在箭头函数之前,每个新函数都定义了它自己的这个值(在构造函数的情况下是一个新对象,在严格模式函数调用中是未定义的,如果函数被称为“对象方法”则是基础对象,等等)。事实证明,面向对象的编程风格并不理想。
#1
2
This is because you are losing the scope in your callback. Modify it to use an arrow function so that you keep 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.
在箭头函数之前,每个新函数都定义了它自己的这个值(在构造函数的情况下是一个新对象,在严格模式函数调用中是未定义的,如果函数被称为“对象方法”则是基础对象,等等)。事实证明,面向对象的编程风格并不理想。