4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

thisを使わないJavaScriptパターン

Last updated at Posted at 2018-03-16

アロー演算子が導入されたからと言ってJavaScriptにおいてthisがややこしいことには変わりがない。以下、よくやる間違い。

class Person {
  constructor({name,age}){
    this.name = name
    this.age = age
  }
  say () {
    console.log(`${this.name} ${this.age}`)
  }
}
const p = new Person({name:'Alice',age:16})
p.say() //OK
setTimeout(()=>{p.say()},1000) //OK
setTimeout(p.say,1000) //NG
const f = p.say
//f() //NG Compile error

もうthis使わないようなコードを書く、と規約にしてもいいんじゃない?

function createPerson({name,age}){
  const say = () => {
    console.log(`${name} ${age}`)
  }
  return {
    say,  //and other method if you like
  }
}
const p2 = createPerson({name:'Alice',age:16})
p2.say() //OK
setTimeout(()=>{p2.say()},1000) //OK
setTimeout(p2.say,1000) //OK
const f2 = p2.say
f2() //OK

継承だってできるし。

function createWizard({name,age,rod}){
  const p = createPerson({name,age})
  const zap = () => {
    console.log(`${rod}!!`)
  }
  return {
    ...p,
    zap,
  }
}
const wiz = createWizard({name:'Alice',age:16,rod:'fire'})
wiz.say()
wiz.zap()

なんとなく参考: https://medium.freecodecamp.org/elegant-patterns-in-modern-javascript-ice-factory-4161859a0eee

4
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?