箭头函数的作用:
- 让this 变得可以理解
- 让代码变得更简洁
箭头函数的基本语法
箭头函数只能做赋值,不能做声明
//ES3的写法
let xxx = function(p1,p2){
console.log(p1)
return 2
}
//箭头函数基本形式
let xx1 = (p1,p2) => {
console.log(1)
return 2
}
//如果只有一个参数,可以不写()
let xx2 = p1 => {
console.log(1)
return 2
}
//如果函数体只有一句话,可以不写{},同时可以不写return,return的结果就是这句话
//如果加return就一定要加{}
let xx3 = (p1,p2) => p1+p2 //(return p1 + p2)
等价于
let xx3 = (p1,p2) => {
return p1 + p2
}
//如果只有一个参数和一句话
let xx4 = p1 => p1 *2
this是call的第一个参数
ES3 支持this,ES6也支持this,但是用箭头函数弱化了this的用法。
- ES3 this的使用方法:
//正常的参数船传递
function f(p1,p2){
// let p1 = arguments[0]
// let p2 = arguments[1]
console.log(p1) //abc
}
f('abc')
p1的值是由f(这个里面的内容决定的。)
p2的值是由f(xx,第二个内容决定的。)
arguments = [f()括号内的内容]
//this的来历
let object = {
name: 'obj',
hi: function(p1,p2){
console.log(this.name)
}
}
object.hi(1,2)
- this 其实是存在的,只是隐藏起来的,JS是接受this.
- this是由.前面的内容决定的
- object.hi()其实是在这样写,object.hi(object),此时括号中的object就是this
- this s是默认存在的,但是人看不到。其实是:function(this,p1,p2)
- object.hi.call(object,1,2) === object.hi(object,1,2) === object.hi(1,2)===object.hi(this,1,2),其中,this = object,1 = p1,2 = p2,即this是call函数的第一个参数
- this不是写代码的时候确定的,而是传过来的。
this的问题,this是call的一个参数,是调用的时候传递的参数,只有在调用的时候才能确定this的值,每个函数都有一个隐含的This。
var controller = {
el: '#app',
init: function(){
var self = this
$(this.el).on('click',this.onClick)
//这里面的this指的是元素
//jquery 源码里面有
//this.onClick.call(元素)
//可以看文档
self.xxx()
//self === controller
},
onClick:function(){
this.getUsers()
},
getUsers: function(){
}
}
controller.init()
controller.init.call(controller)
箭头函数的作用
箭头第一个参数就是参数,没有隐藏this,他没有This的概念,他永远不会接受this。箭头函数的内外this是一样的。他把this当做普通参数来使用。
init: function(){
var self = this
$(this.el).on('click',(p1,p2) => {
this.xxx()
//此时this.xxx()的this和this.el的this是同一个
})
箭头函数的使用
- 数组的每一项平方
var array = [1,2,3,4,5]
//传统做法
for(let i = 0; i < array.length; i++){
array[i] = array[i] * array[i]
}
array
//数组的API做法
array.map(function(number){
return number * number
})
//箭头函数做法
array.map(number=>number*number)
- 箭头函数的连续复用
array.map(number=>number*number)
.map(number=>number + 1) //平方后的每一项加1
.map(number => number *2) //加1后的每一项*2
Vue对象的this使用
只有一层函数的情况下不能使用箭头函数,因为没有办法获取this,所以要像下列代码的形式使用箭头函数。
new Vue({
el:'#ap',
data: {},
methods:{
function(){
//上面的function不能改成this
//此时this已经获取到,是vue实例
//那么下面的嵌套函数可以使用箭头函数
let f = () =>{
}
},
//以下代码不能改成使用箭头函数的形式
onclick: function(){
this.data //要使用This获取数据
}
}
})
面试题
var myObject = {
foo: 'bar',
func: function(){
var self = this; //this就是myObject
console.log('outer func: this.foo = ' + this.foo) //bar
console.log('outer func: self.foo = ' + self.foo) //bar
(function(){
//立即执行函数this是window
//this是window
//这个立即执行函数只会修改this的值,不会修改self的值
console.log('outer func: this.foo = ' + this.foo) //undefined
console.log('outer func: self.foo = ' + self.foo) //bar
}())
}
}
myObject.func()
网友评论