Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialTani Huang
6,952 PointsCan someone explain more detail, why inside Vue methods, function change it to ()=> will run undefined ?
var book = new Vue ({
el: '.book-group',
data: {
title: 't1',
author: 'author1',
summary: 'This is a book',
},
methods: {
sayhello: function() {
alert(this.title)
}
}
})
var book = new Vue ({
el: '.book-group',
data: {
title: 't1',
author: 'author1',
summary: 'This is a book',
},
methods: {
sayhello: ()=> {
alert(this.title)
}
}
})
1 Answer
Chris Shaw
26,676 PointsHi Tani Huang,
The reason for this is because of how arrow functions behave in ES6 (ECMAScript 2015). Unlike the classic anonymous function syntax, arrow functions use lexical scoping which inherits this
from the parent context rather than directly from the current object.
I would recommend you stick with plain old anonymous functions since they will always bind this
correctly and are still perfectly valid.
Happy coding!