Last active
May 11, 2020 08:35
-
-
Save oieioi/2fcb1d4f04cc37dcdaea8288b19204c7 to your computer and use it in GitHub Desktop.
JSのthisとarrowの説明資料
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var user = { name: 'john' } | |
console.log(user) | |
user.hello = function () { | |
// この this == user(レシーバー) になってほしい | |
return "I am " + this.name + "!" | |
} | |
user.callback = function (cb) { | |
console.log('exec callback') | |
console.log(cb()) | |
} | |
// => I am john! | |
console.log(user.hello()) | |
var hello = user.hello; | |
// => I am undefined! | |
// レシーバがないので、this.name = undefinedになる | |
console.log(hello()); | |
// => callback I am undefined! | |
// 実行時にはレシーバがなくなっちゃってるので、undefinedになってしまう | |
user.callback(user.hello) | |
// こうする | |
// => callback I am john! | |
user.callback(function(){ return user.hello() }) | |
class User { | |
constructor (name) { | |
this.name = name; | |
} | |
// arrow Function で this を束縛できる | |
hello = () => { | |
return `I am ${this.name}!`; | |
} | |
} | |
var user = new User('john'); | |
// I am john! | |
console.log(user.hello()) | |
var hello = user.hello | |
// I am john! | |
console.log(hello()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment