Skip to content

Instantly share code, notes, and snippets.

@oieioi
Last active May 11, 2020 08:35
Show Gist options
  • Save oieioi/2fcb1d4f04cc37dcdaea8288b19204c7 to your computer and use it in GitHub Desktop.
Save oieioi/2fcb1d4f04cc37dcdaea8288b19204c7 to your computer and use it in GitHub Desktop.
JSのthisとarrowの説明資料
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