0

Hi I would know how can I use variables of the component in nested function.

Here's an example:

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');

}

Here's what I get in browser dev tool

first  AppComponent {name: Array(4), namev: "helo", isexist: Array(1)};
second undefined

I have some questions How can I access to isexist without using arrow funtion ? why the second this does not contain test element ?

Hamza Haddad
  • 1,516
  • 6
  • 28
  • 48

3 Answers3

2

try lambda here:

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); 
      }
      })
}
Achu
  • 272
  • 2
  • 10
  • Yes with arrow function that works ;) but I have mentioned it , how get the same result before `=>` was out ? – Hamza Haddad May 12 '18 at 16:50
  • that is because of a javascript concept called closures. In javascript each function is an object. before arrow in html 5 we had to use bind function. [bind link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) – Achu May 12 '18 at 16:55
  • 1
    Read this https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch5.md – Nandita Sharma May 12 '18 at 16:56
1

The reason why you cannot access to ifExists without using arrow functions is that this in an arrow function has the same value as the context in which the arrow function was created.

this in a normal anonymous function however, has the value of the context in which the normal function was called from ( In your case, the context and scope of normal function is only the inside of ifExists method.

Omer Gurarslan
  • 979
  • 11
  • 15
1

There's no reason at all to loop, as you're only checking if an array contains an element. You don't even return from map(). The other answers already explain your problem with this, and here's how you should refactor your code (rewrote to plain js to make it work in the snippet, but you get the idea):

class Foo {
  constructor() {
     this.name = ['Angular 6','Angular5','Angular4','Angular2'];
     this.isexist = [];
  }
  
  ifExist(text) {
    if (this.name.includes(text)) this.isexist.push(text);
  }
  
  runner() {
    this.ifExist('Angular 6');
    console.log(this.isexist);
  }
}


new Foo().runner()
baao
  • 71,625
  • 17
  • 143
  • 203