审视js函数定义的两种不同写法,真的完全等价么?有什么区别?
发布于 作者:苏南大叔 来源:程序如此灵动~
现在javascript的世界是百花齐放,各自框架是层出不穷。本文面对最基本的js函数的写法,展开讨论。当然,最基本的事实还是需要承认的。普通情况上来说,这几种写法都是差不多等同的。但是,仔细对比的话,细节上是有较大差异的。

大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔对编程代码的个人理解。本文对js函数的写法做对比讨论。测试环境:node@16.14.2。
以前有篇文章,可以做本文的铺垫:
https://newsn.net/say/js-this.html
基本操作代码
最常见的函数写法,如下:
const sunan = (a, b) => {
console.log("sunan", this, arguments);
return a + b;
}
function sunan2(a, b) {
console.log("sunan2", this, arguments);
return a + b;
}
console.log(sunan(1, 2));
console.log(sunan2(1, 2));客观上来说,这两个函数的效果是一致的。但是,如果在这两个函数稍作修改,打印一下this和arguments的话,就会发现出现了问题。

定义到object上的方法
可以直接定义:
const SN = {
x: 1,
sunan: (a, b) => {
console.log("【sunan】", this, arguments);
return a + b;
},
sunan2: function (a, b) {
console.log("【sunan2】", this, arguments);
return a + b;
}
}
Object.prototype.sunan3 = (a, b) => {
console.log("【sunan3】", this, arguments);
return a + b;
}
Object.prototype.sunan4 = function (a, b) {
console.log("【sunan4】", this, arguments);
return a + b;
}
console.log(SN.sunan(1, 2));
console.log(SN.sunan2(1, 2));
console.log(SN.sunan3(1, 2));
console.log(SN.sunan4(1, 2));表格总结
| 写法 | this | paraments |
|---|---|---|
| () => {} | {} | [Arguments] {'0': {},'1': [Function: require] {}} |
| function xxx (){} | Object [global] {} | [Arguments] { '0': 1, '1': 2 } |
| {x:()=>{}} | {} | [Arguments] {'0': {},'1': [Function: require] {}} |
| {x:function(){}} | { x: 1, sunan: [Function: sunan] | [Arguments] { '0': 1, '1': 2 } |
| xxx.prototype.yyy=()=>{} | {} | [Arguments] {'0': {},'1': [Function: require] {}} |
| xxx.prototype.zzz=function(){} | { x: 1, sunan: [Function: sunan] | [Arguments] { '0': 1, '1': 2 } |
从结果上来看,虽然上面的所有写法返回值结果都是一致的。但是,函数体内部判断this和params的时候,却有着不同的结果。所有的()=>{}中的this和paraments都似乎有些奇怪,而function(){}中的this和params的取值,都符合一般的概念。
结束语
更多js相关经验文章,请点击苏南大叔的博客: