一、函数的属性 length
函数的 length 返回函数参数的个数。
function sayName(name) {
alert(name);
}
function sum(num1, num2) {
return num1 + num2;
}
function sayHi() {
alert("hi");
}
alert(sayName.length); // 1
alert(sum.length); // 2
alert(sayHi.length); // 0
二、函数方法 apply()、call()、
每个函数都包含两个非继承而来的方法:apply() 和 call()。这两个方法的 用途都是在特定的作用域中调用函数,实际上等于设置函数体内 this 对象的值。
- apply() 与 call() 接收第一个参数都是 this.
- apply() 第二个参数是数组,也可以是 arguments 对象。
function sum(num1, num2){
return num1 + num2;
}
function callSum1(num1, num2){
return sum.apply(this, arguments); // 传入 arguments 对象
}
function callSum2(num1, num2){
return sum.apply(this, [num1, num2]); // 传入数组
}
alert(callSum1(10,10)); //20
alert(callSum2(10,10)); //20
- call() 第二个参数必须逐个列举出来的。
function sum(num1, num2){
return num1 + num2;
}
function callSum1(num1, num2){
return sum.apply(this, arguments); // 传入 arguments 对象
}
function callSum2(num1, num2){
return sum.apply(this, [num1, num2]); // 传入数组
}
alert(callSum1(10,10)); //20
alert(callSum2(10,10)); //20
- apply()和 call() 真正的用武之地;它们真正强大的地方是能够扩充函数赖以运行的作用域。
window.color = "red";
var o = { color: "blue" };
function sayColor(){
alert(this.color);
}
sayColor(); //red
sayColor.call(this); //red
sayColor.call(window); //red
sayColor.call(o); //blue
- 通过用 call() 和 apply() 来写一个伪数组可以调用的 forEach 方法
var jiaArr = {
0: 'html',
1: 'css',
2: 'js',
3: 'java',
length: 4
};
Array.prototype.forEach = function (fn) {
for (var i = 0; i < this.length; i++) {
fn(this[i], i)
}
}
Array.prototype.forEach.call(jiaArr, (item, index) => {
console.log(item, index)
})
三、函数方法:bind()
bind()。这个方法会创建一个函数的实例,其 this 值会被绑定到传给 bind() 函数的值。
- 如下例子,sayColor()调用 bind()并传入对象 o,创建了 objectSayColor() 函数。objectSayColor() 函数的 this 值等于 o,因此即使是在全局作用域中调用这个函数,也会看到 "blue"。
window.color = "red";
var o = { color: "blue" };
function sayColor(){
alert(this.color);
}
var objectSayColor = sayColor.bind(o);
objectSayColor(); //blue