箭头函式
传统函式
const callName = function(someone){
return '我是' + someone;
}
console.log(callName('皮杰先生'));
箭头函式
// 箭头函式
// 若是程序码内容为表达式时,不需要大括号{}
// 若只有一个参数 可省略括号
const callName = someone => '我是' + someone;
console.log(callName('皮杰先生'));
与传统函式不同之处
传统函式
var nums = function(){
console.log(arguments);
}
nums(1,2,3,4,50,100);
箭头函式
// arguments is no defined
var nums = () =>{
console.log(arguments);
}
nums(1,2,3,4,50,100);
解决方式
其余参数
原型是阵列(与 arguments 不同)
var nums = (...arg) =>{
console.log(arg);
}
nums(1,2,3,4,50,100);
箭头函式没有自己的 this
传统函式
var myName = '全域';
var person = {
myName:'皮杰先生',
callName: function(){
console.log('1',this.myName); // 1 皮杰先生
setTimeout(function(){
console.log('2',this.myName); // 2 全域
console.log('3',this); // window
})
}
}
person.callName();
箭头函式
var myName = '全域';
var person = {
myName:'皮杰先生',
callName: function(){
console.log('1',this.myName); // 1 皮杰先生
setTimeout(()=>{
// 这里会用外层作用域的 this
console.log('2',this.myName); // 2 皮杰先生
console.log('3',this); // person
})
}
}
person.callName();
var myName = '全域';
var person = {
myName:'皮杰先生',
callName: ()=>{
console.log('1',this.myName); // 1 全域
setTimeout(()=>{
// 这里会用外层作用域的 this
console.log('2',this.myName); // 2 全域
console.log('3',this); // window
})
}
}
person.callName();
也无法透过 call,apply,bind 重新给予 this
const family = {
myName:'123',
}
const fn = (a,b) =>{
console.log(this,a,b); // window 小黑 小白
}
fn.call(family,'小黑','小白');
const fn = function(a){
this.name = a;
}
const ArrowFn = a =>{
this.name = a;
}
console.log(fn.prototype);
console.log(ArrowFn.prototype); // undefined
const a = new fn('a');
console.log(a);
const b = new ArrowFn('b');
console.log(b);
那今天的介绍就到这里
若有任何问题 或 内容有误
都可以跟我说唷
这两天会介绍到 JS 内 var 与 let 的差异,今天跟明天分别介绍两点。 JS 的 var 以...
Web 应用程序选单多样化,早期最常见的多半树状选单,直至手机问世後汉堡选单(hamburger m...
来找设计师一起 side project,前後端 / UIUX 皆可ㄛ。配对单连结: https:...
HALCON是由德国MVtec公司开发的一套完善的商用的机器视觉算法软件, 在欧洲以及日本的工业界已...
链结串列(Linked List)常用来处理相同类型资料,在不连续的记忆体位置,以随机的方式储存,由...