熟悉javaScript语言的同学都知道,javaScript是一门弱类型语言,比如定义变量,不需要定义变量的类型。
有人说,学起来比较容易,但是越往后,发现里面有好多坑。在前端项目中,经常看到一些技术大牛用this关键字用的飞起,而我们这些小菜鸟,就只能丈二和尚摸不着头脑,不理解其中究竟。最近也在学习javaScript,研究了下this关键字,闲话不多说,进入正题。
javaScript中的this可以是全局对象,当前对象或者任意对象,这完全取决于函数的调用方式。而javaScript中函数调用的方式有以下几种:作为对象方法调用,作为函数调用,作为构造函数调用,以及使用apply或call调用。下面按照不同的调用方式,分别讨论下this的含义。
- 作为对象方法调用
函数也是对象,因此一个对象的属性可以是一个函数,此时该函数被称为对象的方法,在使用这种调用方式时,this被自然绑定到该对象。
var person = {
name : "Lily",
age: 23,
say : function(name, age){
console.log("name is "+this.name+" age is "+this.age)
}}
person.say("lucy", 34); //返回结果:name is Lily age is 23
此时this指向的是person对象,而person.name = "Lily", person.age = 23;
因此返回的结果是name is Lily age is 23。
2. 作为函数调用
函数也可以直接被调用,此时this绑定到全局对象,在浏览器中,window就是该全局对象
function person(age) {
this.age = age;
}
person(24);
接下来执行赋值语句,相当于隐式的声明了一个全局变量
3.作为构造函数调用
javaScript支持面向对象式编程,与主流的面向对象式编程语言不同,javaScript并没有类(class)的概念,而是使用基于原型(prototype)的继承方式。构造函数以大写字母开头,提醒调用者使用正确的方式调用,如果正确,this绑定到新创建的对象上。
function Person(){
this.name = "lily";
this.age = 23;
this.say = function(name, age){
this.name = name;
this.age = age;
console.log("name is "+this.name+" age is "+this.age);
}
}
var student = new Person();
student.say("lisa", 45);// name is lisa age is 45 此时 this指向的是student对象。
4. 使用apply或call调用
apply和call是函数调用对象的方法,他们允许切换函数执行的上下文环境(context),即this绑定的对象
var person = {
name:"lily",
age:23,
say: function(name, age){
this.name = name;
this.age = age;
console.log("name is "+this.name+" age is "+this.age);
}
}
person.say.call(student, "kate", 25);
apply和call类似,只是后面的参数通过一个数组传入,而不是分开传入,两者的方法定义:
call(thisArg [, arg1, arg2,arg3,….])
apply(thisArg[, argArray]);
两者都是将某个函数绑定到某个具体对象上使用,自然此时的this会被显示的设置为第一个参数。
小结下;
1.当函数作为对象的方法调用时,this指向该对象。
2.当函数作为单纯的函数调用时,this指向全局对象(严格模式时,为undefined)
3.构造函数中的this指向新创建的对象
4.嵌套函数中的this不会继承上层函数的this,需要用一个变量保存上层函数的this
var name = "Lily";
var person = {
name : "Lisa",
say: function(sth){
var that = this;
var sayHello = function(sth){
console.log("name is "+that.name)
}
sayHello(sth);
}
}
person.say("kobi") // name is Lisa 此时that指向为person中name属性。
5. 如果在函数中使用了this,只有在该函数直接被某对象调用时,该this才指向该对象。
6. eval函数使用比较频繁,该函数执行时的作用域是当前作用域,
var name = "Lily";
var person = {
name: "Lisa",
say: function(){
eval("console.log(this.name)");
}
};
person.say(); //Lisa person对象在调用eval方法,调用者的执行环境中的this就被eval方法继承下来了。
由于个人能力有限,希望通过自己一些见解能帮到大家,不喜请勿喷