我正在学习有关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步,不要使用箭头函数,它的'this'是不同的。第2步迭代'this.cars',而不是'cars' –
,但是,对于你的最后一个例子,不要使用箭头作为toString,但是请使用forEach函数的箭头...所以(简写)'toString(){this .cars.forEach(car => ...' –
'cars'是一个对象属性,它必须用'obj.cars'语法访问,不能以'cars'的形式访问它,它不是局部变量。 ,没有将'this'隐式附加到属性中,就像其他语言一样,必须引用'person.cars'。 – jfriend00