ES6出现的Arrow function,看起来简短许多,但却充满许多陷阱(限制),所以充份了解箭头函数後,再往後使用上也会减少一些Bug,或是fix bug也会比较有头绪。
// 一般表达式写法
let buySomething = function(something) {
return `我买了${something}`;
}
// 箭头函式
let buySomething = (something) => {
return `我买了${something}`;
}
// 箭头函式省略return
let buySomething = (something) => `我买了${something}`;
// 只有一个参数可升略括号
let buySomething = something => `我买了${something}`;
// 没有参数时,一定要有括号
let buySomething = () => '我买了一些物品';
let randomParamFunc = () => {
console.log(arguments);
}
randomParamFunc(1,2,3,4,5)
// arguments is not defined
一般函数的例子:
let user = {
id:123,
name:"Gino",
height:180,
getHeight() {
return this.height
}
};
console.log(user.getHeight()) // 180
let getHeight = user.getHeight
console.log(getHeight()) // undefined
箭头函数的例子:
function test() {
return a => {
console.log(this.a) // this会继承test function的this
}
}
let objA = {
a:100
}
let objB = {
b:200
}
let test1 = test.call(objA);
test1.call(objB); // 100
test函数内部的箭头函数会补捉呼叫test函数时的this,所以会补捉到this绑定到objA,绑定後就无法再变更了,所以最後一行所显示出的是100而不是200,另外也可以发现在箭头函数中,是没办法使用apply、call、bind去指定this的指向。
const makeCar = (brand, modal, color) => {
this.brand = brand;
this.modal = modal;
this.color = color
}
const toyotaCar = new makeCar('Toyota','RAV4','white') //makeCar is not a constructor
针对DOM事件监听的函数中,this会指向全域(window),导致无法正常运作。
let targets = document.getElementsByTagName('div');
let changeColor = () => {
this.style.color = 'blue' // this指向window
}
for(let i = 0; i < targets.length; i++) {
targets[i].addEventListener('click',changeColor)
}
在prototype中新增方法如果有用到this,并不会如意的指向呼叫的object,而是会指向全域(window)。
function MakeCar(brand, modal, color){
this.brand = brand;
this.modal = modal;
this.color = color
}
MakeCar.prototype.carInfo = () => {
console.log(`这是一台${this.brand},型号为${this.modal}的${this.color}色汽车`)
}
const car = new MakeCar('Toyota','RAV4','white');
car.carInfo(); // 这是一台undefined,型号为undefined的undefined色汽车
参考文章:
大家会不会很好奇跟朋友在LINE上最常讲的话是什麽? 或是跟朋友讲了几通电话呢? 前阵子很流行把LI...
有些针对 @vue/cli 的全局配置,例如你惯用的包管理器和你本地保存的 preset,都保存在 ...
那进入到第二天的,今天我们先来了解基本 Google Apps Script 的设定方式! ㄧ、怎麽...
先备知识: 基本python能力 : 熟悉各基本型态,认识串列、字典、函式、class 了解深度学习...
Day 3 - Reverse Integer 大家好,我是毛毛。ヾ(´∀ ˋ)ノ 废话不多说开始今...