Arrow Functions
Fat Arrow Syntax
// normal style.
var sum = function( a, b ) {
return a + b;
}
// using fat arrow syntax.
var sum = ( a, b ) => {
return a + b;
}
// Because of the simple code, you don't need a pair of curly bracket
var sum = ( a, b ) => a + b;
Context Binding
function testBinding(val) {
this.val = val
setTimeout(
function() {
console.log(this.val) // 这个是访问不到的,这里的this是setTimeout函数中的this
},
1000
)
}
testBinding(999)
es5中 solution1
function testBinding(val) {
this.val = val
var self = this
setTimeout(
function() {
console.log(self.val) // 通过外部定义变量
},
1000
)
}
testBinding(999)
es5中使用bind
function testBinding(val) {
this.val = val
setTimeout(
function() {
console.log(this.val)
}.bind(this), // bind 方法将 setInterval 函数参数的上下文绑定到 this。
1000
)
}
testBinding(999)
tip
在 ES6 中,箭头函数带有自动上下文绑定。因此无需考虑上下文绑定。
ES6中使用箭头函数
function testBinding(val) {
this.val = val
setTimeout(
() => console.log(this.val),
1000
)
}
testBinding(999)