var b = newB() //TypeError: B is not a constructor
不绑定 arguments,用 rest 参数…解决
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*常规函数使用arguments*/ functiontest1(a) { console.log(arguments) //1 } /*箭头函数不能使用arguments*/ vartest2 = a => { console.log(arguments) } //ReferenceError: arguments is not defined /*箭头函数使用reset参数...解决*/ lettest3 = (...a) => { console.log(a[1]) } //22
test1(1) test2(2) test3(33, 22, 44)
使用 call()和 apply()调用
由于 this 已经在词法层面完成了绑定,通过 call() 或 apply() 方法调用一个函数时,只是传入了参数而已,对 this 并没有什么影响:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var obj = { value: 1, add: function (a) { varf = v => v + this.value//a==v,3+1 returnf(a) }, addThruCall: function (a) { varf = v => v + this.value//此this指向obj.value var b = { value: 2 } return f.call(b, a) //f函数并非指向b,只是传入了a参数而已 }, }