直接上代码
'use strict';
let data = {
count: 10,
item: [],
getItems: () => {
let count = this.count;
console.log(this); //{}
console.log(count); //undefined
for (var i = 0; i < count; i++) {
this.item.push(i);
}
}
};
data.getItems();
console.log(data.item); //[]
上面这段代码一目了然,方法getItems采用箭头函数,this指向全局空间。
'use strict';
let data = {
count: 10,
item: [],
getItems() {
let count = this.count;
console.log(this); //{ count: 10, item: [], getItems: [Function: getItems] }
console.log(count); //10
for (var i = 0; i < count; i++) {
this.item.push(i);
}
}
};
data.getItems();
console.log(data.item); //[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
上面这段代码的getItems方法采用方法名(){}的形式,得到了想要的结果。
'use strict';
let data = {
count: 10,
item: [],
getItems: function() {
let count = this.count;
console.log(this); //{ count: 10, item: [], getItems: [Function]}
console.log(count); //10
for (var i = 0; i < count; i++) {
this.item.push(i);
}
}
};
data.getItems();
console.log(data.item); //[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
上面的代码是es5的写法,一样得到了想要的结果,但是打印出来的this跟前面一组代码有所不同
网友评论