突然对这个有点模糊,再找回复习一下
关于this的指向
如果是一个单独的函数 this是指向window
function a(){
var username = "五毛";
console.log(this.username); //undefined
console.log(this); //Window
}
a();
如果是一个对象,对象里面有一个方法 这时候 谁调用 this指向谁
var a = {
username:"五毛",
fn:function(){
console.log(this.username); //五毛
onsole.log(this); //a对象
}
}
a.fn(); //a这个对象调用的方法 所以 this指向a
如果是构造函数 构造函数的this指向新建的那个对象
function Person(uesrname,age){
this.usernme = username;
this.age = age;
}
var a = Person(wumao,18)
注意
window.setTimeout()和window.setInterval()的函数中的this有些特殊,里面的this默认是window对象。
关于修改this指向
一般通过call,apply,bind来修改this的指向,下面这个是MDN上对call的解释
call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。
call和()一样都能去调用函数,但是不同的是 call能通过里面的参数来对函数内部的this进行重新指向
例如(call的第一个参数是this指向的位置,第二第三...是传入的参数)
function fn(a, b){
console.log(this);
console.log(a + b);
};
// fn(1, 2); // window 3
fn.call( {name: "五毛", age: 18}, 100, 200, 300, 400 );// {name: "五毛", age: 18} 300
apple方法和call类似,唯一的区别就是 它只有两个参数,第一个参数是this的指向,第二个参数是个伪数组,里面存着要传入的每个参数。
bind法法
bind方法
语法: var newFn = fn.bind(thisArg);
作用: 创建并返回新的函数,新函数和fn函数结构一样,但是新函数内的this指向被固定了,固定成了bind的参数
var fn = function () {
console.log("hello world");
console.log(this);
}
var fn2 = fn.bind( "hello kitty" );
fn() // hello world window
fn2() // hello world hello kitty
bind固定之后 里面的this就是永久指向bind里面的参数