Javascript 在嵌套函数的角度中使用此关键字
嗨,我知道如何在嵌套函数中使用组件的变量 下面是一个例子:Javascript 在嵌套函数的角度中使用此关键字,javascript,typescript,ecmascript-6,ecmascript-5,Javascript,Typescript,Ecmascript 6,Ecmascript 5,嗨,我知道如何在嵌套函数中使用组件的变量 下面是一个例子: export class AppComponent implements OnInit { name = ['Angular 6','Angular5','Angular4','Angular2']; isexist: string[]=[]; ifExist(text){ var that= this; console.log("first ",this); var test="test"; let exis
export class AppComponent implements OnInit {
name = ['Angular 6','Angular5','Angular4','Angular2'];
isexist: string[]=[];
ifExist(text){
var that= this;
console.log("first ",this);
var test="test";
let exist= this.name.map(function (elm){
if(elm==text) {
console.log(this);
this.isexist.push(elm); // works with that.isexist.push(elm);
}
})
}
ngOnInit() {
this.ifExist('Angular 6');
}
以下是我在浏览器开发工具中得到的信息
first AppComponent {name: Array(4), namev: "helo", isexist: Array(1)};
second undefined
我有一些问题
如何在不使用箭头功能的情况下访问isexistisexist
?
为什么第二个此
不包含测试
元素?请在此处尝试lambda:
ifExist(text){
var that= this;
console.log("first ",this);
var test="test";
let exist= this.name.map((elm)=>{
if(elm==text) {
console.log(this);
this.isexist.push(elm); // works with that.isexist.push(elm);
}
})
}
请在此处尝试lambda:
ifExist(text){
var that= this;
console.log("first ",this);
var test="test";
let exist= this.name.map((elm)=>{
if(elm==text) {
console.log(this);
this.isexist.push(elm); // works with that.isexist.push(elm);
}
})
}
如果不使用箭头函数,则无法访问
ifExists
,原因是此箭头函数中的与创建箭头函数的上下文具有相同的值
但是,在普通匿名函数中,此
具有从中调用普通函数的上下文的值(在您的情况下,正常函数的上下文和范围只是ifExists
方法的内部。不使用箭头函数就无法访问ifExists
,原因是箭头函数中的此
与创建箭头函数的上下文具有相同的值
但是,在普通匿名函数中,此
具有从中调用普通函数的上下文的值(在您的例子中,普通函数的上下文和范围仅在ifExists
方法的内部。根本没有理由循环,因为您只检查数组是否包含元素。您甚至不从map()返回。)
。其他答案已经解释了您在这方面的问题,下面是您应该如何重构代码(重写为纯js以使其在代码段中工作,但您明白了这一点):
class-Foo{
构造函数(){
this.name=['angular6','Angular5','Angular4','Angular2'];
this.isexist=[];
}
ifExist(文本){
if(this.name.includes(text))this.isexist.push(text);
}
跑步者(){
这个。如果存在('Angular 6');
console.log(this.isexist);
}
}
new Foo().runner()
完全没有理由循环,因为您只检查数组是否包含元素。您甚至不会从map()
返回。其他答案已经解释了您的问题,下面是您应该如何重构代码(重写为纯js以使其在代码段中工作,但您明白了这一点):
class-Foo{
构造函数(){
this.name=['angular6','Angular5','Angular4','Angular2'];
this.isexist=[];
}
ifExist(文本){
if(this.name.includes(text))this.isexist.push(text);
}
跑步者(){
这个。如果存在('Angular 6');
console.log(this.isexist);
}
}
new Foo().runner()
Yes与arrow函数配合使用;)但我已经提到过,如何在=>
出现之前获得相同的结果?这是因为一个名为closures的javascript概念。在javascript中,每个函数都是一个对象。在html 5中的arrow函数之前,我们必须使用bind函数。阅读这个Yes与arrow函数配合使用;)但是我已经提到过,在=>
出现之前,如何获得相同的结果?这是因为一个名为闭包的javascript概念。在javascript中,每个函数都是一个对象。在html 5中的箭头之前,我们必须使用绑定函数。请阅读以下内容