函数属性length
函数的 length 为 形参 的 length
,
arguments
的 length
为实参的length。
例如:
1 2 3 4 5 6
| function foo(a, b) { console.log(arguments.length); }
foo(); console.log(foo.length);
|
函数方法 apply、call、bind
call()方法与 apply()方法的作用相同,它们的区别仅在于接收参数的方式不同, apply是接受数组,call是正常参数。
bind()是es5新加的方法。这个方法会创建一个函数的实例,方便后续使用,其 this 值会被绑 定到传给 bind()函数的值。
以上三个方法 都会绑定函数的作用域。
apply 和 call
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| function construct(name, age) { this.name = name; this.age = age; }
function people(name, age) { construct.apply(this, arguments); this.getName = function () { console.log("I am " + this.name); }
this.getAge = function () { console.log("My age is " + this.age); }
}
var girl = new people('Lily', 50);
girl.getName(); girl.getAge();
|
bind
最经典的应用场景就是react组件内函数的this指向问题。或者统一使用箭头函数,不要this,或者使用bind函数,bind(this)到组件的this上
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| var foo = { data: { name: '123', age: 321 }, printData: function () { function bar() { console.log(this.data); } bar.bind(this)(); } }
foo.printData();
|