// 普通函數
let fun = function () {
console.log('原始函數')
}
fun()
// 沒有形參的時候
let fun1 = () => console.log('我是箭頭函數')
fun1()
// 隻有一個形參的時候,可以省略小括号
let fun2 = a => console.log(a)
fun2('我是a')
// 兩個及兩個以上
let fun3 = (x, y) => console.log(x, y)
fun3(30, 31)
// 函數體隻有一條語句或者是表達式的時候,大括号{}可以省略
// 會自動傳回語句執行的結果,或者是表達式的結果
let fun4 = (x, y) => x + y
fun4(30, 31)
// 函數體不止一條語句或者是表達式的時候,大括号{}不可以省略
let fun5 = (x, y) => {
console.log(x, y)
return x + y
}
fun5(30, 31)
箭頭函數的this:
箭頭函數沒有自己的this,箭頭函數的this不是調用的時候決定的,而是在定義的時候處在的對象就是它的this
箭頭函數的this看外層是否有函數,如果有,外層函數的this就是内部箭頭函數的this,如果沒有,則this是window
let btn1 = document.getElementById('btn1')
let btn2 = document.getElementById('btn2')
btn1.onclick = function () {
console.log(this)
}
btn2.onclick = () => { // 外層沒有函數,指向window
console.log(this) /
}
===============================================================================
let obj = {
name: '箭頭函數',
getName: function () {
btn2.onclick = () => { // this指向obj
console.log(this)
}
}
}
===============================================================================
let obj = {
name: '箭頭函數',
getName: () => { // 外層沒有函數,this指向window
btn2.onclick = () => { // 外層函數指向window,this指向window
console.log(this)
}
}
}
箭頭函數沒有arguments,caller,callee
箭頭函數本身沒有arguments,如果箭頭函數在一個function内部,它會将外部函數的arguments拿過來使用。
箭頭函數中要想接收不定參數,應該使用rest參數...解決。
let B = (b)=>{
console.log(arguments);
}
B(2,92,32,32); // Uncaught ReferenceError: arguments is not defined
let C = (...c) => {
console.log(c);
}
C(3,82,32,11323); // [3, 82, 32, 11323]
箭頭函數通過call和apply調用,不會改變this指向,隻會傳入參數
let obj2 = {
a: 10,
b: function(n) {
let f = (n) => n + this.a;
return f(n);
},
c: function(n) {
let f = (n) => n + this.a;
let m = {
a: 20
};
return f.call(m,n);
}
};
console.log(obj2.b(1)); // 11
console.log(obj2.c(1)); // 11
箭頭函數沒有原型屬性
var a = ()=>{
return 1;
}
function b(){
return 2;
}
console.log(a.prototype); // undefined
console.log(b.prototype); // {constructor: ƒ}
箭頭函數傳回對象時,要加一個小括号
var func = () => ({ foo: 1 }); //正确
var func = () => { foo: 1 }; //錯誤
const add = x => y => y + x;
//相當于
function add(x){
return function(y){
return y + x;
};
}
let a = {
foo: 1,
bar: () => console.log(this.foo)
}
a.bar() //undefined bar函數中的this指向父作用域,而a對象沒有作用域,是以this不是a,列印結果為undefined
=======================================
function A() {
this.foo = 1
}
A.prototype.bar = () => console.log(this.foo)
let a = new A()
a.bar() //undefined 原型上使用箭頭函數,this指向是其父作用域,并不是對象a,是以得不到預期結果