企业 网站备案,梧州门户网,2014年网站开发语言,手机做网站视频#xff08;许多人所谓的成熟#xff0c;不过是被习俗磨去了棱角#xff0c;变得世故而实际了。那不是成熟#xff0c;而是精神的早衰和个性的消亡。真正的成熟#xff0c;应当是独特个性的形成#xff0c;真实自我的发现#xff0c;精神上的结果和丰收。——周国平许多人所谓的成熟不过是被习俗磨去了棱角变得世故而实际了。那不是成熟而是精神的早衰和个性的消亡。真正的成熟应当是独特个性的形成真实自我的发现精神上的结果和丰收。——周国平 箭头函数
箭头函数表达式的语法比函数表达式更简洁并且没有自己的thissuper。箭头函数表达式更适用于那些本来需要匿名函数的地方并且它不能用作构造函数。
箭头函数特点
1. 不需要编写funtion而是这种更简单的箭头替代
const fun function () {console.log(普通函数);
};
const fun2 () {console.log(箭头函数);
};
fun();
fun2();2. 箭头函数没有自己的this而是向上查找
更确切的说是箭头函数的外层如果有普通函数那么箭头函数的this就是这个外层的普通函数的this箭头函数的外层如果没有普通函数那么箭头函数的this就是全局变量。
const Person function () {this.age 0;setInterval(function () {this.age; // 由于setInterval属于全局此时的this属于全局console.log(this.age);}, 1000);
};
new Person();// 为了解决上面的问题可以单独定义一个that来解决
const Person2 function () {this.age 0;const that this;setInterval(function () {that.age; // 由于使用的是thatthat指向外层的this所以正常运行console.log(that.age);}, 1000);
};
new Person2();// 有了箭头函数就更简单了不需要定义that
const Person3 function () {this.age 0;setInterval(() {this.age; // 由于使用了箭头函数箭头函数自身没有this所以指向了外层函数的thisconsole.log(this.age);}, 1000);
};
new Person3();3. 箭头函数没有arguments
arguments 是一个对应于传递给函数的参数的类数组对象。 可以看出因为箭头函数自身没有arguments所以它的arguments指向了外层函数的arguments。而普通函数有自己的arguments所以能打印出4。
const func1 function (a, b, c) {const fun2 function (d, e, f) {console.log(arguments[0]);};fun2(4, 5, 6);
}func1(1, 2, 3);const func2 function (a, b, c) {const fun3 (d, e, f) {console.log(arguments[0]);};fun3(4, 5, 6);
}func2(1, 2, 3);那么如何解决这个问题
使用剩余参数一个类数组的入参结构使用显式参数也就是入参的参数名
const func1 function (a, b, c) {const fun2 function (...arg) {console.log(arg[0]);};fun2(4, 5, 6);
}func1(1, 2, 3);const func2 function (a, b, c) {const fun3 (...arg) {console.log(arg[0]);};fun3(4, 5, 6);
}func2(1, 2, 3);const func3 function (a, b, c) {const fun4 (d, e, f) {console.log(d);};fun4(4, 5, 6);
}func3(1, 2, 3);4. 箭头函数不能使用new进行实例化
箭头函数除了不能new之外它还没有prototype原型属性。 这是因为箭头函数没有this就导致无法绑定实例。因为不能实例化成对象所以就没有原型链了。
const Fun () { };
new Fun();
// TypeError: Fun is not a constructor更高级的箭头函数
相比较传统的函数箭头函数在部分场景下可以直接省去返回值和花括号写法更简洁明了。
const list [1, 2, 3];
const result list.find((function (v) {if (v 3) {return v;}
}))
console.log(result); // 3
const result2 list.find((v) v 3);
console.log(result2); // 3