参考 Fun Fun Function 的 how good are class arrow functions in javascript 内容。
class Warrior{
constructor(element){
this.element = element
}
ready(){
return `${this.element} is ready for attaching `
}
}
const aWarrior = new Warrior("zidea")
const button = {
onClick : null
}
button.onClick = aWarrior.ready
button.onClick()
运行的结果不难想象应该为 undefined is ready for attaching undefine 。这是因为 button onclick 引用了 Warrior 的 attach 的方法。但是这里 button 中并没有 element 这个属性。所以 undefined。这也就是我们常说的 this 指向的问题。
button.onClick = aWarrior.ready.bind(aWarrior)
button.onClick()
我们通过 bind 的方法将我们方法绑定到指定的对象,这样我们的方法就有了 context 也就是上下文。这样就解决了问题,这样写法我们在 jquery 的事件绑定是最常见不过的了。
当然我们也可以也使用 es6 的箭头函数作为 ready 属性,这个箭头好处就是我无需再写 bind 来讲方法绑定到指定对象,箭头方法中 this 对象。
ready = ()=>{
return `${this.element} is ready for attaching `
}
不通过这样做还是有性能问题的,
constructor(element){
this.element = element
this.ready = this.ready.bind(this)
}
ready (){
return `i am ready for attaching ${this.element}`
}
这种写法想必我们在写 react 时候会经常遇到这种写法。这样同样可以解决 this 的指向的问题。
每一次都会创建一个函数
const createWarrior = function(element){
return {
element:element,
ready: function(){
return `i am ready for attaching ${this.element}`
}
}
}
const createWarrior = function(element){
return {
ready: function(){
return `i am ready for attaching ${element}`
}
}
}
我们对 createWarrior 进行改造。
const createWarrior = element => ({
ready: function(){
return `i am ready for attaching ${element}`
}
})