1.先看一个例子:
1 <script> 2 function show() { 3 console.log('aluoha'); 4 } 5 show(); 6 </script>
2. 改写成简单的箭头函数:
1 var show = () => console.log('箭头:aluoha'); 2 show();
3. 1 包含return 的常规函数:
1 function show() { 2 return 10; 3 } 4 console.log(show());
3.2 包含return 的箭头函数:
错误写法:
1 var show = () =>return 10; 2 console.log(show());
运行结果:
正确写法:
1 var show = () => { 2 return 10; 3 }; 4 console.log(show()); 5
小结:在箭头函数中,有return 返回值时,需要使用{}把函数体包裹起来
4.1 箭头函数的参数
1 var show = val => val; 2 console.log(show(100));
4.2 只有一个参数也可以写成:
1 var show = val => { 2 return val; 3 } 4 console.log(show(10));
4.3 一个参数,也可以加括号()包含:
var show = (val) => { return val; } console.log(show(100));
4.4 箭头函数,多个参数:
1 var add = (a, b) => { 2 return a + b; 3 } 4 console.log(add(10, 20));
4.5 箭头函数不可实例化:
1 var show = () => console.log('aluoha'); 2 show(); 3 new show(); //报错
正常函数可以实例化:
1 function show() { 2 console.log('aluoha'); 3 } 4 show(); 5 new show();
5.1 this指向:
1 var show = () => { 2 console.log(this); //this->window 3 } 4 show();
5.2 this调用:实际调用 window.a
1 var a = 101; 2 var show = () => { 3 console.log(this.a); 4 } 5 show();
5.3.1 this指向宿主对象:(不传参)
1 var userName = 'global'; 2 function User(name) { 3 this.userName = name; 4 5 this.showUserInfo = () => { 6 return this.userName; 7 }; 8 this.showName = function() { 9 return this.userName; 10 }; 11 } 12 var oUser = new User(); 13 console.log(oUser.showUserInfo()); 14 console.log(oUser.showName());
5.3.2 传参调用:
1 var userName = 'global'; 2 function User(name) { 3 this.userName = name; 4 5 this.showUserInfo = () => { 6 return this.userName; 7 }; 8 this.showName = function() { 9 return this.userName; 10 }; 11 } 12 var oUser = new User("aluoha"); 13 console.log(oUser.showUserInfo()); 14 console.log(oUser.showName());
http://www.cnblogs.com/huanying2015 博客随笔大多数文章均属原创,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利