简体   繁体   中英

using lexical this in ES6

I was learning about lexical this in ES6, and I countered this example :

let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : function(){
    for(let car of cars){
            console.log(`${this.name} has ${car}`)
        }
  }
}

person.toString();

so let's say I want to convert the toString function to an array function so I'll have this :

let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : () => {
    for(let car of cars){
            console.log(`${this.name} has ${car}`)
        }
  }
}

person.toString();

in this example cars is undefined, why I'm getting that, and how can I call cars from the person object in that example.

the same goes for this :

let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : () => {
    cars.forEach(car => console.log(`${this.name} has ${car}`));
  }
}

person.toString();

The first example is already broken.

in this example cars is undefined, why I'm getting that

There is no variable with name cars . Whether or not you are using an arrow function doesn't make a difference.

how can I call cars from the person object in that example.

Use a method or function expression and reference it with this.cars :

let person = {
  name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString() {
    for(let car of this.cars){
            console.log(`${this.name} has ${car}`)
        }
  }
}

Arrow functions cannot be used as instance methods , because in instance methods you don't want lexical this . Learn more: Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?

Because of your arrow function that your this apply to your object which the function you called.

correct

let person = {
  name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : function() {
   this.cars.forEach(car=>{
        console.log(`${this.name} has ${car}`)
    })
  }
}

person.toString();

The last arrow function in foreach is apply this of your object that why you didn't need to use clourse like this.cars.forEach(...)(this.name) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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