arguments
- 它是一个类数组对象,包含调用函数时传入的所有参数
- 以function关键字定义的才会有arguments (箭头函数没有)
- callee 是指向 arguments 对象所在函数的指针
- eg
function text(num) {
if (num <= 1) {
return 1;
} else {
return num * arguments.callee(num - 1);
}
}
text(3);
console.log(text(3));
this
- 标准函数
- 箭头函数
- 在事件回掉或定时回掉this指向并非自己想要的对象
- 将回调函数写成箭头函数可以解决
- 箭头函数中的this会保留定义该函数时的上下文
function King() {
this.royaltyName = 'Mack';
setTimeout(() => {
console.log(this.royaltyName);
}, 1000);
}
function Queen() {
this.royaltyName = 'Marray';
setTimeout(function() {
console.log(this.royaltyName);
}, 1000);
}
new King();
new Queen();
函数属性和方法
- 属性
- length
- prototype
- prototype是保存引用类型所有实例方法的地方
- 方法
- apply()
function sum(num1, num2) {
return num1 + num2;
}
function callSum1(num1, num2) {
return sum.apply(this, arguments);
}
function callSum2(num1, num2) {
return sum.apply(this, [num1, num2]);
}
console.log(callSum1(10,10));
console.log(callSum2(10,20));
- call()
- eg
function sum(num1, num2) {
return num1 + num2;
}
function callSum(num1, num2) {
return sum.call(this, num1, num2);
}
console.log(callSum(10,10));
- bind()
- eg
// bind
window.color = 'red'
let o = {
color: 'blue'
}
function sayColor() {
console.log(this.color)
}
let objSayColor = sayColor
objSayColor()
let objSayColorBind = sayColor.bind(o)
objSayColorBind()
- call() 和 apply区别
- 直接传arguments对象或一个数组用 apply()
- 单个传用 call()