简体   繁体   English

无法从angular4中的嵌套函数访问它

[英]Cannot Access this from nested function in angular4

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的变量,当我尝试从嵌套函数访问它时,它给我一个未定义的。

eg 例如

@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
});

}

}

This is because you are losing the scope in your callback. 这是因为您正在丢失回调中的范围。 Modify it to use an arrow function so that you keep this 将其修改为使用箭头功能,以便保留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. 事实证明,面向对象的编程风格并不理想。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM