ES6 Arrow Functions
ES6 introduces Arrow Functions.
var foo = (a) => a;
foo("hello word"); //hello word
Equivalent to:
var foo = function(a){
return a
}
foo("hello word"); //hello word
With a single parameter, you can even omit the parentheses:
var foo = a => a;
foo("hello word"); //hello word
If the function has no parameters, you must include the parentheses:
var foo = () => {
alert("hello word");
};
As an event handler:
document.addEventListener('click', event => {
console.log(event)
})
Callback:
$("button").hover(
()=>{
// mouse enter
console.log("mouse enter");
},
()=>{
// mouse leave
console.log("mouse leave");
})
With arrow functions, this inherits from the enclosing scope. Here’s an example:
var oImage = new Image()
var oImage2 = new Image()
document.getElementById("button").onclick=() => {
// No outer scope, so this is undefined
console.log(this); // this is undefined
oImage.src="https://gss0.bdstatic.com/5eR1dDebRNRTm2_p8IuM_a/res/img/richanglogo168_24.png";
oImage2.src="https://gss0.bdstatic.com/5eR1dDebRNRTm2_p8IuM_a/res/img/richanglogo168_24.png";
// Using arrow function here, this inherits from the enclosing scope,
// but since the enclosing this is also undefined, this is still undefined
oImage.onload=() => {
console.log(this)// this is undefined
}
// Not using arrow function
oImage2.onload=function(){
console.log(this)// this will be the image object
}
}
Using a traditional function for the outer scope:
var oImage = new Image()
var oImage2 = new Image()
document.getElementById("button").onclick=function(){
// Not using arrow function, so this is the button
console.log(this); // this is the button
oImage.src="https://gss0.bdstatic.com/5eR1dDebRNRTm2_p8IuM_a/res/img/richanglogo168_24.png";
oImage2.src="https://gss0.bdstatic.com/5eR1dDebRNRTm2_p8IuM_a/res/img/richanglogo168_24.png";
// Using arrow function, this inherits from the enclosing scope
oImage.onload=() => {
console.log(this)// this is still the button
}
// Not using arrow function
oImage2.onload=function(){
console.log(this)// this will be the image object
}
}