this
在JavaScript中访问全局变量,访问函数内部变量,大家都知道,this,是用起来最舒服的一个指针。对于this有几个特点
1.在预编译过程中this指向window(全局)
function test(){
var a = 123;
var b = 456;
}
test();
/*在test函数预编译阶段,AO中除了有a和b还有两个参数,arguments和this,这里的arguments是实参列表,而这里的this现在指的就是window
AO{
argument : [],
this : window,
a : 123,
b : 456
}
*/
2.在全局作用域中 this指向window(全局)
这个应该谁都明白,当访问变量的环境是全局的时候,this指向window。
3.call/apply 改变this指向
通过obj.call(this),改变this指向。借用别人家的方法构造自己的对象。
function Person(name,age){
this.name = name ;
this.age = age;
}
function Student(name,age,sex){
Person.call(this,name,age);
//或者 Person.apply(this,[name,age]);
this.sex = sex;
}
var student new Student();
4.obj.方法,此时方法里面的this指向当前对象,而当前对象就是obj
var name = "zhou";
function Person (){
this.name = "wang";
this.age = 20;
this.say = function(){
console.log(this.name);
}
var person = new Person();
person.say();
//输出 "wang"
JavaScript语言我个人感觉是最有意思的了,我也是一个初学者,遇到问题,喜欢在博客上分享,
也希望能帮到大家。
一个初学者,有什么不足或者纰漏的话,希望在下面评论出来,相互学习,共同进步。
--主页传送门--