- 方法调用
var age = 38;
var obj = {
age: 18,
getAge: function() {
console.log(this.age);
}
};
obj.getAge(); //18
--------------------------------------------------
// 变式:
var fn = obj.getAge;
fn();
- 函数调用,里面的this指向的是window
var age = 38;
var obj = {
age: 18,
getAge: function() {
var fn = function() {
console.log(this.age);
};
fn();
}
};
obj.getAge();//38
- 构造函数调用:this指向调用它的对象
var age = 38;
var obj = {
age: 18
};
var getAge = function() {
console.log(this.age);
};
obj.get = getAge;
obj.get(); //18
- call 和 apply 上下文调用模式,this指向谁?指向的是传入的对象
var arr = [1, 3, 4, 6, 7, 555, 333, 13]
var max = arr[0]
for (let i = 0; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i]
}
}
console.log(max) //555
console.log(Math.max(1, 2, 3, 4, 5))//5
//apply 输入的参数(arr指的是this ,arr即输入格式必须为数组)
console.log(Math.max.apply(arr, arr)) //=== Math.max(1,3,4,6,7,555,333,13) //555
//apply 输入的参数(arr指的是this ,后面的即为格式数组的内容)
console.log(Math.max.call(arr, 1, 3, 4, 6, 7, 555, 333, 13)) //555
网友评论