-
Notifications
You must be signed in to change notification settings - Fork 3.3k
第 58 题:箭头函数与普通函数(function)的区别是什么?构造函数(function)可以使用 new 生成实例,那么箭头函数可以吗?为什么? #101
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
箭头函数是普通函数的简写,可以更优雅的定义一个函数,和普通函数相比,有以下几点差异: 1、函数体内的 this 对象,就是定义时所在的对象,而不是使用时所在的对象。 2、不可以使用 arguments 对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替。 3、不可以使用 yield 命令,因此箭头函数不能用作 Generator 函数。 4、不可以使用 new 命令,因为:
new 过程大致是这样的: function newFunc(father, ...rest) {
var result = {};
result.__proto__ = father.prototype;
var result2 = father.apply(result, rest);
if (
(typeof result2 === 'object' || typeof result2 === 'function') &&
result2 !== null
) {
return result2;
}
return result;
} |
引入箭头函数有两个方面的作用:更简短的函数并且不绑定this。箭头函数与普通函数不同之处有:
|
"函数体内的 this 对象,就是定义时所在的对象,而不是使用时所在的对象。" 也不能说是定义时所在的对象吧,应该是定义时所在的作用域中的 this 值,因为 JS 的静态作用域的机制,this 相当于一个普通变量会向作用域链中查询结果,同时定义时所在对象也并不等于所在对象中的 this 值。 |
区别: 箭头函数带来的好处:
|
箭头函数不能通过new关键字调用原因
箭头函数并没有 另外, 可以参考
|
没有自己的this,无法指向自身。构造函数生成对象需要调用函数初始化属性。 |
我也来献个丑: 箭头函数是ES6的写法,与function最大的不同是this的指向问题, 而function 的this是看情况指向的,一般优先级是 new > bind > obj. > window 前端新手,有错误的话请不要客气,直接指出,谢谢。 |
箭头函数与普通函数区别:
// hi (3)不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替。 (4)不可以使用yield命令,因此箭头函数不能用作 Generator 函数。 |
剪头函数没有自己的 this,不能用作构造函数 |
箭头函数由于this的指向在它定义的时候已经确定了(它外层代码的this),并不像其他普通函数在执行的时候确定this的指向,所以在new 的时候不会改变this的指向(在new 的过程中this会变成空对象然后指向对应的地方) |
let num1 = [1,2,2,1]; let res = []; console.log(fn(num1,num2)) |
箭头函数的this是上下文的this,它会从自己作用域的上一层继承this |
箭头函数不能被 new 执行,不能用作构造函数。因为箭头函数没有prototype ,也没有自己的this,不能调用call和apply |
为什么不能当Generator 函数使用 |
箭头函数具有以下特性:
|
箭头函数与普通函数(function)的区别是什么?构造函数(function)可以使用 new 生成实例,那么箭头函数可以吗?为什么
|
你好,我想请问一下,后面判断result的用意是什么呢? |
1)、箭头函数不同于一般函数: (2)一般函数有arguments,而箭头函数没有arguments,但可以使用rest参数(剩余参数) (3)一般函数可以当作构造函数,而箭头函数不能当作构造函数,因为箭头函数没有自己的this (1)、当只有一个形参时可以省略圆括号; (2)、当函数体只一条语句并且该语句会作为返回值返回时,可以省略花括号及return关键词 |
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions
|
|
No description provided.
The text was updated successfully, but these errors were encountered: