es6 函数的扩展
代码:
<script> //默認值的用法 /* function log(x, y) { y = y || "word"; console.log(x, y); } log("hello"); */ /* function add(...values) { let sum = 0; for (let val of values) { sum += val; } return sum; } console.log(add(1, 2, 3, 4, 5, 5, 5, 5)); */ /* function foo(n) { return n; } */ //=====> 等價于 let foo = n => n; /* //1個參數的時候 let add = value => value; //2個參數 let add2 = (value1, value2) => value1 + value2; let add3 = (value1, value2) => { value1 += 1; let sum = value1 + value2; return sum * 100; } console.log(add(1), add2(1, 2), add3(1, 2)); */ /* let PageHandle = { id: 123, init: function() { document.addEventListener('click', (event) => { console.log(this); this.doSomeThings(event.type); }, false); //正常的funtion(event){}如果函數沒有bind函数绑定上面的this,this指向,會指到#document,但是箭头函数没有这个问题。 }, doSomeThings: function(type) { console.log(`事件類型:${type},當前id:${this.id}`); } }; PageHandle.init(); */ //箭頭函數不能用new來實例化 //错误示例: let fn = () => 1; let newFn = new fn(); //上面代码报错,报错显示:Uncaught TypeError: fn is not a constructor,面试题。 //箭頭函數沒有this指向問題; </script>
1,箭头函数函数体中 this 的指向是定义时 this 的指向。如代码中
PageHandle.init定义时的this,就是PageHandle这个对象。
箭头函数版:
let PageHandle = {
id: 123,
init: function() {
document.addEventListener('click', (event) => {
console.log(this);
this.doSomeThings(event.type);
}, false); //正常的funtion(event){}如果函數沒有bind函数绑定上面的this,this指向,會指到#document,但是箭头函数没有这个问题。
},
doSomeThings: function(type) {
console.log(`事件類型:${type},當前id:${this.id}`);
}
};
PageHandle.init();
function 版:需要用bind函数绑定定义时的对象,代码如下:
let PageHandle = {
id: 123,
init: function() {
document.addEventListener('click', function (event) {
console.log(this);
this.doSomeThings(event.type);
}.bind(this), false); //正常的funtion(event){}如果函數沒有bind函数绑定上面的this,this指向,會指到#document,但是箭头函数没有这个问题。
},
doSomeThings: function(type) {
console.log(`事件類型:${type},當前id:${this.id}`);
}
};
PageHandle.init();
其他笔记:可能面试会问到的。
//箭頭函數不能用new來實例化
//错误示例:
let fn = () => 1;
let newFn = new fn();
//上面代码报错,报错显示:Uncaught TypeError: fn is not a constructor,面试题。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库