网站建设与管理好处,外语网站建设,wordpress 外贸企业模板下载,遵义市住房和城乡建设厅网站箭头函数返回对象
// 这种情况要要用(),否则会将对象的{}解释为块
const fn (a, b) ({a:1, b:2})箭头函数的特点
this指向由外层函数的作用域来决定#xff0c;它本身没有this#xff0c;不能通过call、apply、bind改变不能作为构造函数使用不可以使用arguments对象 (a, b) ({a:1, b:2})箭头函数的特点
this指向由外层函数的作用域来决定它本身没有this不能通过call、apply、bind改变不能作为构造函数使用不可以使用arguments对象该对象在函数体内不存在可用rest代替不可以使用yield命令因此箭头函数不能用作 Generator 函数。
function foo() {console.log(this, this)return (a) {console.log(a, this.a)}
}
var obj1 { a: 2 };
var obj2 { a: 3 };
var bar foo.call(obj1)
bar.call(obj2) // 2所有的内层函数都是箭头函数都没有自己的this它们的this其实都是最外层foo函数的this。
function foo() {return () {return () {return () {console.log(id:, this.id);};};};
}var f foo.call({id: 1}); // foo是普通函数可以通过call改变this指向var t1 f.call({id: 2})()(); // id: 1
var t2 f().call({id: 3})(); // id: 1
var t3 f()().call({id: 4}); // id: 1定义对象的方法
定义对象的方法且该方法内部包括this且该方法内部包括this不应使用箭头函数定义
const p {eat: function () {console.log(this-eat, this)},sleep: () {console.log(this-window, this)}
}
p.eat() // p
p.sleep() // window 以下例子bind与箭头函数都能让this指向实例
arguments
function foo() {const a () {console.log(arguments)}a()
}
foo(1, 2, 3, 4) // [1,2,3,4] 箭头函数内无arguments取外层的function foo() {setTimeout(() {console.log(arguments)})
}
foo(1, 2, 3, 4) // [1,2,3,4] 箭头函数内无arguments取外层的嵌套的箭头函数
// 非常语义化
function insert(value) {return {into: function (array) {return {after: function (afterValue) {array.splice(array.indexOf(afterValue) 1, 0, value);return array;}};}};
}insert(2).into([1, 3]).after(1); //[1, 2, 3]// 改写为箭头函数效果相同但是可读性差
let insert (value) ({into: (array) ({after: (afterValue) {array.splice(array.indexOf(afterValue) 1, 0, value);return array;
}})});insert(2).into([1, 3]).after(1); //[1, 2, 3]应用场景
简单的函数表达式内部没有this引用没有递归事件绑定解绑定内层函数表达式需要调用this且this应与外层函数一致时保证指向vue实例
const sortArr (...nums) nums.sort((a, b) a - b)
console.log(sortArr(5, 4, 1, 10)) // [1, 4, 5, 10]