函数属性length
函数的 length 为 形参 的 length
,arguments
的 length
为实参的length。
例如:1
2
3
4
5
6function foo(a, b) {
console.log(arguments.length);
}
foo(); // 0
console.log(foo.length); // 2
函数方法 apply、call、bind
call()方法与 apply()方法的作用相同,它们的区别仅在于接收参数的方式不同, apply是接受数组,call是正常参数。
bind()是es5新加的方法。这个方法会创建一个函数的实例,方便后续使用,其 this 值会被绑 定到传给 bind()函数的值。
以上三个方法 都会绑定函数的作用域。
apply 和 call
1 | function construct(name, age) { |
bind
最经典的应用场景就是react组件内函数的this指向问题。或者统一使用箭头函数,不要this,或者使用bind函数,bind(this)到组件的this上1
2
3
4
5
6
7
8
9
10
11
12
13
14var foo = {
data: {
name: '123',
age: 321
},
printData: function () {
function bar() {
console.log(this.data); // 这里面的this是指向 foo.printData 这个function,而不是foo对象
}
bar.bind(this)();
}
}
foo.printData(); // { name: '123', age: 321 }