跟变数一样 JavaScript 在 ES6 为函式新添加一种写法,他和传统函式有以下差异:
除了以上和传统函式不同,箭头函式本身一个可以缩写特性,先来看一下范例:
这是原本传统函式:
const sayHi = function(name){
return `Hello ${name}`
}
console.log(sayHi('Ryder')) //Hello Ryder
如果是使用 箭头函式 可以省略 return
以及 { }
const sayHi = (name)=> `Hello ${name}`
console.log(sayHi('Ryder')) //Hello Ryder
当参数只有一个时,也可以将包着参数的 ()
给省略。
const sayHi = name => `Hello ${name}`
console.log(sayHi('Ryder')) //Hello Ryder
this
的指向。this
,箭头函式的 this
会绑定到定义时所在的位置,跟呼叫方法无关,先来看看范例:var name = 'Ryder'
var obj1 = {
name: 'Jack',
showName:function(){
console.log(this.name)
}
};
var obj2 = {
name: 'Jack',
showName:() => {
console.log(this.name)
}
};
obj1.showName() // Jack
obj2.showName() // Ryder
上面有提到,箭头函式的 this
会绑定到定义时所在的位置,这是什麽意思呢?
简单来说就是: 当该实体、变数在哪里建立, this
就会指向哪里,而上面范例的 obj
正是建立在 window 下的,因此 this
是指向 window。
在函式基本章节有提到,传统函式能够透过 arguments 这个关键字获得该函式所有参数,而这方法在箭头函式中无法使用,如范例:
function Fn1(){
console.log(arguments) // Arguments(2) ['Ryder', 123, ...]
}
Fn1('Ryder', 123)
const Fn2 = () => {
console.log(arguments) // VM940:2 Uncaught ReferenceError: arguments is not defined
}
Fn2('Ryder', 123)
不过这点可以使用 ES6 新增的其余参数,来获得全部参数资料,只需要在参数部分填上 ...arg
之後的 arg
便可获得全部参数资料。(arg 可自定义名称
const Fn3 = (...arg) => {
console.log(arg) //['Ryder', 123]
}
Fn3('Ryder', 123)
上面有提到箭头含是没有自己的 this
,因此建构式函式自然无法使用
const TShirt = (color,material,size) => {
this.color = color
this.material = material
this.size = size
}
const BlackTShit = new TShirt('black','棉','L') //TShirt is not a constructor
箭头函式的 this
是无法使用 call
、apply
、 bind
上述绑定 this
功能,箭头函式的 this
会是固定的。
const obj = {
name:'Ryder'
}
const Fn1 = () => {
console.log(this) }
function Fn2(){
console.log(this)
}
Fn1.call(obj) // Window
Fn2.call(obj) // {name: 'Ryder'}
<<: 从 IT 技术面细说 Search Console 的 27 组数字 KPI (23) :KPI 总表
挑战目标: MockNative Camp前端 周末也是很多事要做,每天大概都晚上9点到12点是铁人...
使用绝对定位 / 相对定位 设计版型 https://ithelp.ithome.com.tw/up...
前言 今天玩转黑胶唱片,Audio Web API 接起来~~ Audio Web API Audi...
我们终於进到写程序的部分了,前几天我们都在教学基本的使用,今天就让我来教大家吧!我们就先开到程序档的...
资讯审计人员需要能识别和了解所设计的控制,以确保输入和输出各种业务和应用程序的数据授权、完整性和准确...