JS中的this究竟代表什么,这是在程序运行时根据上下文环境确定,可以分为以下几种情况。
在全局作用域中,this指向window对象。
console.log(this);//指向window对象
this.x = 5//在全局作用域内创建一个x
//与this.x = 5的等价情况:
//var x = 5;
//x = 5;
JS中函数有两种,直接调用的函数称为普通函数,通过new创建对象的函数称为构造函数。
构造函数的this指向它所创建的对象,如:
function Person(name){
this.name = name;//this指向该函数创建的对象person
}
var person = new Person("chaimm");
普通函数的this指向window对象。 若上述例子,直接执行Perosn函数,则其中this代表window对象,因此该函数执行后会创建一个全局的name。
function Person(name){
this.name = name;//this指向window
}
Person("chai");//当作普通函数执行,this指向window对象
对象中的this指向当前对象,如:
var person = {
name : "chaimm",
getName : function(){
return this.name;
}
}
上述代码中this指向函数getName所属的对象。 但是,如果一个对象的函数中又嵌套了一个函数,这个函数的this指向的却是window,而并不是其外层的对象。
var person = {
name : "chaimm",
setName : function(name){
(function(name){
this.name = name; //此时this并不代表person对象,而是代表window对象
})(name);
}
}
上述示例中,person对象中有一个getName函数,而getName函数内部又有一个函数,这个函数内部的this指向window对象,而非person对象,这是JS的一个bug!一般作如下处理,规避这个bug:
var person = {
name : "chaimm",
setName : function(name){
var thar = this;//将this赋给that
(function(name){
that.name = name;//此时that指向person对象
})(name);
}
}
我们在person对象的第一层函数中,将this赋给局部变量that,然后在第二层函数中使用that,此时that指向person对象,可对person的属性进行操作。
var person = {
name : "chaimm",
getName : function(){
return this.name;
}
}
//将getName函数赋给一个新的变量
var newGetName = person.getName;
//通过新的变量调用这个函数,这个函数中的this将指向window
newGetName();//若全局作用域中没有name,则将返回undefined
这两个函数都能手动指定被调用函数内部的this指向哪个对象。
//定义一个构造函数
var Person = function(name){
this.name = "";
this.setName = function(name){
this.name = name;
}
}
//创建两个对象
var personA = new Person("A");
var personB = new Person("B");
//使用personA的setName函数去修改personB的name属性
personA.setName.apply(personB,["C"]);