this
作为函数内部的属性,它指向的是函数执行的环境变量,即当前的函数作用域。
在 JavaScript 中 this
主要有以下五种情况的指向:
-
纯粹的函数调用(匿名函数的执行环境具有全局性)
function test(){ console.log(this); } test();
var test = function(){ console.log(this); } test();
此时
this
在nodejs
环境中指向的是全局变量 global:
在浏览器中指向的是window对象:
-
作为对象方法被调用
var test = { sayName:function(){ console.log(this); } }; test.sayName();
此时
this
指向上一级对象即test
,打印结果为:{ sayName: [Function: sayName] }
-
作为构造函数被调用
function Test(){ this.name = 1; } var test = new Test(); console.log(test.name); ------------------------ 1
此时的
this
指向的是这个新对象test
-
apply()或call()调用
function fun(){ console.log(this.name); } var obj = { name:"obj" }; var obj2 = { name:"obj2" }; fun.apply(obj);//obj fun.call(obj2);//obj2
调用
apply()
和call()
方法,可以将一个对象指定为第一个参数,此时这个对象就是函数执行的this
。在 apply 模式中如果使用 null,就是函数模式,如果使用对象,就是方法模式。
当call或apply的第一个参数为null || undefined时 this指向window ||global
apply()
和call()
方法不同在于:
call()
可以将实参在对象之后依次传递,apply()
需要将实参封装到数组中统一传递。
call(obj,1,2,.....);
apply(obj,[1,2,3,....]);
例1:
function fun(a,b){ console.log("a="+a); console.log("b="+b); console.log(this.name); } var obj = { name:"obj" }; var obj2 = { name:"obj2" }; fun.apply(obj,[1,2]); //输出:a=1 b=2 obj fun.call(obj2,1,2); //输出:a=1 b=2 obj2
例2:
var obj = { name:"obj", sayName:function(){ console.log(this.name); } }; var obj2 = { name:"obj2" }; obj.sayName.apply(obj2); //打印出 obj2
-
调用bind()方法
test.bind();
不传参数默认指向全局变量global,浏览器指向window。
test.bind(obj);
不执行test函数,只是更改this
指向,返回更改了this
指向后的test函数。
传递参数的两者表示:
test.bind(obj)(5,6)
test.bind(obj,5,6)
function test(a,b){ console.log(this,a,b); } var obj = {}; test.bind();//不执行 test.bind(obj)(1,2);//{} 1 2 test.bind(obj,1,2)();//{} 1 2