一、this是谁
- 作为普通函数调用/自执行,this在全局/自执行(函数名())时,this指向window,实际上并不是指向了window,而是指向了null,被解释成了window。
- 使用
"use strict"开启严格模式,在es5的严格模式下,自执行,this指向undefined。
function fn(){
this.xx = 123;
}
fn();
console.log(window.xx);
"use strict";
function fn(){
console.log(this);
}
fn();
var fn2 = function(){
console.log(this);
}
fn2();
document.onclick = function(){
(function(){
console.log(this);
})()
}
function t3(){
function t4(){
console.log(this);
}
t4();
}
t3();
- 作为对象的方法来调用的时候,this指向的是调用那一瞬间的调用者,即调用对象。不管函数声明时,this属于谁。
var bark = 'hahaha';
var dog = {name:'xiaohua',bark:"wangwang"};
var show = function(){
alert(this.bark);
}
var cat = {bark:'miaomiao'};
dog.t = show;
cat.t = dog.t;
console.log(cat);
cat.t();
(cat.t = dog.t)();
(dog.t)()
console.log(cat.t = dog.t);
function fn1(){
function fn2(){
console.log(this.bark);
}
fn2();
}
dog.t = show;
console.log(dog);
dog.t();
dog.fn1= function(){
(function(){
console.log(this.bark);
})();
};
dog.fn1()
var name = "The window";
var obj = {
name:"my name",
getNameFunc:function(){
return function(){
return this.name;
}
}
}
console.log(obj.getNameFunc()());
- 作为构造函数调用时,js中没有类的概念,创建对象是用构造函数来完成的,或者直接用{}来写对象。
function Dog(name, age){
this.name = name;
this.age = age;
this.bark = function(){
alert(this.name);
}
}
var dog = new Dog("虎子", 2);
dog.bark();
function Pig(){
this.age = 99;
return "abc";
}
var pig = new Pig();
console.log(pig);
- call、apply、bind可以改变this指向。
二、call、apply
- call和apply都是在函数执行时,扭转this指向
- call:语法格式,函数.call(对象,参数1,参数2......);
- apply:语法格式,函数.apply(对象,[参数1,参数2.......]);
function t(num){
console.log('我的真实年龄是' + this.age);
console.log('但我一般告诉别人' + (this.age-num));
}
var lily = {name:'lily',age:20};
t.call(lily,2);
console.log(lily);
var obj = {};
function a(x,y){
console.log(x+y);
console.log(this);
}
a.apply(obj,[3,4]);
a.call(obj,3,4);
box.onclick = function(){
console.log(this);
fn.call(this,100,200);
};
wrap.onclick = fn;
function fn(x,y){
console.log(this);
this.style.width = x + 'px';
this.style.height = y + 'px';
}
function a(x,y){
console.log(this);
}
a.call();
a.call(100);
a.call('haha');
a.call(true);
a.call(null);
a.call(this);
a.call([1,2,3]);
三、bind
- 写在函数(不是声明)表达式中,不立即执行,扭转this指向。
- 传参:在表达式中传参,类似于call;在执行时传参,但失去了本身的意义。
document.onclick = function(){
onsole.log(this);
}.bind(window);
var a = function(x,y){
console.log(x+y);
console.log(this);
}.bind(document,10,20);
a();
var a = function(x,y){
console.log(x+y);
console.log(this);
}.bind(document)(10,1);