this
- 普通函数 window 调用者
console.log(this); //window
// this指向:
// 1、普通函数:window,调用者
function fn () {
console.log(this);
}
fn(); //window
- 构造函数 实例化对象
function Perosn (uname, age) {
this.uname = uname;
this.age = age;
console.log(this);
}
let obj1 = new Perosn('阿飞', 22);
console.log(obj1);
let obj2 = new Perosn('李寻欢', 23);
console.log(obj2);
- 方法 调用者
let obj = {
uname : '张三丰',
age : 22,
fei : function () {
console.log(this);
}
}
obj.fei();
- 事件处理函数 事件源
document.addEventListener('click', function () {
console.log(this);
}); //#document
- 定时器 window调用者
window.setInterval(function () {
console.log(this);
}, 1000)
- 自调用函数 window调用者
;(function () {
console.log(this);
})() //window
function fn () {
console.log(this);
}
document.addEventListener('click', fn); //#document
动态指定普通函数中 this 的指向
- call
使用call方法调用函数, 同时指定this的指向
使用 call 方法调用函数时,第1个参数为 this 指定的值
call 方法的其余参数会依次自动传入函数做为函数的参数
function fun (a, b) {
console.log(this, a, b)
}
let obj = {uname : '张三丰', age : 22};
// // call:
// // 函数.call(this,arg1, arg2,......)
// // 函数调用call、call会调用函数执行,在执行的过程中,改变this的指向
fun.call(obj, 1, 2);//Object 1 2
let obj = {
uname : '张三丰',
age : 22,
fei : function () {
console.log(this);
}
}
let o = {
uname : '李寻欢',
sex : '男'
}
obj.fei.call(o); //指向对象o
- apply
apply:函数.apply(this, [参数1, 参数2])
apply 方法能够在调用函数的同时指定 this 的值
使用 apply 方法调用函数时,第1个参数为 this 指定的值
apply 方法第2个参数为数组,数组的单元值依次自动传入函数做为函数的参数
4. let obj = {
uname : '张三丰',
age : 22,
taiji : function () {
console.log(this);
}
}
let o = {uname : '张无忌', age : 16};
obj.taiji.apply(o); //this指向了o
5. // 数组:
let arr = [23, 66, 33, 19, 4, 7];
let re = Math.max.apply(null, arr);
console.log( re ); //66
6. // ... rest参数:剩余参数,函数,解构赋值
// ... 扩展运算符:数组,字符串,对象
let arr = [23, 66, 33, 19, 4, 7];
// ...扩展运算符
let re = Math.max(...arr);
console.log(re);//66
- Bind 方法不会调用函数,而是创建了一个指定了this值的新函数
bind:函数.bind(this, arg1, arg2,…);
function fn (a, b) {
console.log(this, a, b);
}
let obj = {uname : '李寻欢', age : 22};
// let re = fn.bind(obj);re();
fn.bind(obj, 123, 456)();//Object 123 456
let btn = document.querySelector('input');
btn.addEventListener('click', function () {
// 禁用按钮
this.disabled = true;
// 开启定时器
setTimeout(function () {
this.disabled = false;
}.bind(this), 5000);
});
总结:
// call:函数.call(this, arg1, arg2,......);
// apply:函数.apply(this, [arg1, arg2,......])
// bind:函数.bind(this, arg1, arg2,......)