Поэтому, когда вы используете функцию с ключевым словом function
, она создает новую область видимости для этого, чтобы сослаться на приведенный ниже пример
const obj = {
size: 10,
testFunc() {
console.log(this, 'now obj')
const func = function () {
// this now refers to function its currently in
}
const otherFunc = () => console.log(this, 'refers to obj still')
},
testFunc2: () => {
console.log(this, 'now window')
}
}
любые вопросы, дайте мне знать, и я буду радпомощь
const obj = {
size: 10,
vueMethod(url) {
console.log(this.size, 'this now refers to obj')
const img = new Image();
const self = this;
img.onload = function() {
console.log(this, 'this now refers to img')
console.log(self.size, 'but you can reassign this to a var outside the scope');
self.size = {
width: this.width,
height: this.height
}
};
// mocking the onload dont include this
img.onload();
img.src = url;
}
}
obj.vueMethod()