当前位置:网站首页>ES6箭头函数的使用
ES6箭头函数的使用
2022-07-23 22:29:00 【InfoQ】
前言
起步
function fun() {
return 100;
}
console.log(fun()); //100const fun = function() {
return 100;
}
console.log(fun()); //100const fun1 = () => {
return 100;
}
console.log(fun1()); //100const fun2 = x => x;
console.log(fun2(100)); //100- ()中定义参数,如果只有一个参数,()可以省略
- {}中写函数体,如果函数体中只有返回值,可以不写return
箭头函数与普通函数的区别
举个例子
let obj = {
name: '小明',
age: 3,
sayName() {
setTimeout(function() {
console.log("我是" + this.name);
}, 500)
}
}
obj.sayName();我是undefinedlet obj = {
name: '小明',
age: 3,
sayName() {
setTimeout(function() {
console.log(this);
}, 500)
}
}
obj.sayName();let obj = {
name: '小明',
age: 3,
sayName() {
let self = this;
setTimeout(function() {
console.log("我是" + self.name);
}, 500)
}
}
obj.sayName();我是小明使用箭头函数
let obj = {
name: '小明',
age: 3,
sayName() {
setTimeout(() => {
console.log("我是" + this.name);
}, 500)
}
}
obj.sayName();我是小明我想你们和我都有同样的一个疑惑:为什么使用箭头函数就可以实现了呢?箭头函数与普通函数的区别
- this指向不同
- 普通函数:谁调用这个函数,
this指向谁 - 箭头函数:在哪里定义函数,
this指向谁
片尾
边栏推荐
- Programming in the novel [serial 17] the moon bends in the yuan universe
- ospf终极实验——学会ospf世纪模板例题
- 为了一劳永逸而写的数独
- 小说里的编程 【连载之二十】元宇宙里月亮弯弯
- MySQL的 DDL和DML和DQL的基本语法
- Still worrying about xshell cracking, try tabby
- Inspiration from Buffett's shareholders' meeting 2021-05-06
- 思源笔记的字体比其他的编辑器(Atom,VSC,sublime)内字体渲染更细更淡
- [Matplotlib drawing]
- Programmation JDBC pour MySQL
猜你喜欢
随机推荐
synthesizable之Verilog可不可综合
Use of [golang learning notes] package
zk 是如何解决脑裂问题的
U++ learning notes tsubclassof()
Memory search - DP
[golang learning notes] is parameter transfer in go language value transfer or reference transfer
JDBC programming of MySQL
小说里的编程 【连载之十八】元宇宙里月亮弯弯
Crazy bull market, where to go in the second half? 2021-04-30
Life always needs a little passion
记忆化搜索 - DP
Inspiration from Buffett's shareholders' meeting 2021-05-06
TreeMap
[acwing] weekly competition
Programming in the novel [serial 16] the moon bends in the yuan universe
Is it safe to open a VIP stock account on your mobile phone?
人生总需要一点激情
How ZK solves the problem of cerebral fissure
Programming in the novel [serial 18] the moon bends in the yuan universe
Can Verilog of synthetizable be integrated









