在ES6

2017-07-04 52 views
0

我正在学习有关ES6词汇this,我反驳这个例子中使用的词汇是:在ES6

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

person.toString(); 

所以我们说,我想给ToString函数转换为数组功能,所以我也会有这样的:

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

person.toString(); 

在这个例子中cars是不确定的,为什么我收到了,我怎么能叫cars在这个例子中person对象。

这同样适用此:

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

person.toString(); 
+1

第1步,不要使用箭头函数,它的'this'是不同的。第2步迭代'this.cars',而不是'cars' –

+0

,但是,对于你的最后一个例子,不要使用箭头作为toString,但是请使用forEach函数的箭头...所以(简写)'toString(){this .cars.forEach(car => ...' –

+0

'cars'是一个对象属性,它必须用'obj.cars'语法访问,不能以'cars'的形式访问它,它不是局部变量。 ,没有将'this'隐式附加到属性中,就像其他语言一样,必须引用'person.cars'。 – jfriend00

回答

3

第一个例子已经打破。

在这个例子中 cars

是不确定的,为什么我收到

没有与名称cars没有变量。无论您是否使用箭头功能都没有区别。

如何在该示例中从person对象中调用cars

使用的方法或函数表达式,并与this.cars引用它:

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

箭功能不能被用作实例方法,因为实例方法,你不想词汇this做。了解更多:Arrow function vs function declaration/expressions: Are they equivalent/exchangeable?

0

由于您的箭头功能,您的this适用于您调用的函数的对象。

正确

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

person.toString(); 

foreach最后一箭功能是适用的对象,你为什么没有需要使用像clourse的this.cars.forEach(...)(this.name)此。

+0

*“你不需要像this.cars.forEach ...)(this.name)“*对我没有意义。 –