深入理解JS this
阮一峰博客链接http://www.ruanyifeng.com/blog/2010/04/using_this_keyword_in_javascript.html
this是Javascript语言的一个关键字。
它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。比如,
??? function test(){ ??? this.x = 1; ??? }
阮老师说this 指的是调用函数的那个对象
情况二:作为对象方法的调用
函数还可以作为某个对象的方法调用,这时this就指这个上级对象
var x = 1;
function test(){
// this.x = 2;
alert(this.x);
}
var o={};
o.x = 3;
o.m = test;
o.m()
情况三 作为构造函数调用
所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象。
什么是构造函数?
为了解决从原型对象生成实例的问题,Javascript提供了一个构造函数(Constructor)模式。
所谓"构造函数",其实就是一个普通函数,但是内部使用了this
变量。对构造函数使用new
运算符,就能生成实例,并且this
变量会绑定在实例对象上。
function Cat(name,color){ this.name=name; this.color=color; }
比如,猫的原型对象现在可以这样写,
var cat1 = new Cat("大毛","黄色"); var cat2 = new Cat("二毛","黑色"); alert(cat1.name); // 大毛 alert(cat1.color); // 黄色
几道题
??name = ‘seven‘; ??function test(){ ??????this.name = ‘alex‘; ??????this.func = function(){ ??????????alert(this.name) ??????} ??} ???var obj = new test(); ???obj.func() ?//alex
??name = ‘seven‘; ??function test(){ ??????this.name = ‘alex‘; ??????this.func = function(){ ???????????(function(){ ???????????????alert(this.name) ???????????})() ??????} ??} ???var obj = new test(); ???obj.func() // seven
深入理解JS this,作用域
原文地址:http://www.cnblogs.com/yuyang26/p/7845906.html