JSFiddle - React, Tailwind, and code Playground
by sj82516
JavaScript
console.log('範例一');
const number = [1,2,3];
const result = number.map((n)=> n*2);
console.log(result);
const result2 = number.map((n)=>{value:n});
console.log(result2);
//[undefined, undefined, undefined]
const result3 = number.map((n)=>({value:n}));
console.log(result3);
// [{value:1}, {value:2}, {value:3}]
let sum = -6;
console.log('範例二');
// 前者的this為adder,因為是adder執行;後者為undefined!
const adder = {
sum: 0,
add(number){
console.log("add function context: " ,this);
number.forEach(function(n){
console.log("forEach function context: ", this);
this.sum += n;
})
}
}
// error: Cannot read property 'sum' of undefined
// adder.add([1,2,3]);
console.log(adder.sum);
//使用Arrow function後,可以發現兩者的this 都是相同的
const adder2 = {
sum: 0,
add(number){
console.log("add function context: " ,this);
number.forEach((n) => {
console.log("forEach function context: ", this);
this.sum += n;
})
}
}
adder2.add([1,2,3]);
console.log(adder2.sum);
//如果又多包一層arrow function,兩者都變成undefined
const adder3 = {
sum: 0,
add:(number)=>{
console.log("add function context: " ,this);
number.forEach((n) => {
console.log("forEach function context: ", this);
this.sum += n;
})
}
}
//adder3.add([1,2,3]);
console.log(adder3.sum);
console.log('範例三');
// Arrow Function不可再次用bind 改變context
const adder4 = {sum:0};
const add = (number)=> number.forEach(n=>this.sum+=n);
//adder4.add = add.bind(adder4);
//adder4.add([1,2,3])
const add2 = function(number){
number.forEach(n=>this.sum+=n);
}
adder4.add2 = add2.bind(adder4);
adder4.add2([1,2,3]);
console.log(adder4.sum);
console.log('範例四');
//使用Arrow function的隱性參數都不見了
const add3 = (x,y)=>{return arguments};
const result4 = add3(3,5);
console.log(result4);
const add4 = function(x,y){return arguments};
const result5 = add4(3,5);
console.log(result5);