javascript中的this

关于js中的this,记住这句话:那个对象实例调用this所在的函数,那么this就代表哪个对象实例。
function test() { 
	alert(this.x); 
} 
var o = {}; 
o.x = 1; 
o.m = test; 
o.m(); //1 


console.group("xxxx");
function test() { 
	this.x = 1; 
} 
var o = new test(); 
//alert(o.x);//1 
console.log(o.x);
console.groupEnd("xxxx");


function test3(){
  this.x = 3;
}
test3();
alert(x);//这个函数中,this指的window,可以这样理解,test3() 即 window.test3();
		//所以test3()中的this就指的window,所以x是一个全局变量。


var o = {prop:37};
function my(){
  return this.prop;
  //alert(this.prop);
}
o.f = my;
console.log(o.f());//37,注意o.f()和o.f的差别。暂时还没完全理解这二者的具体差异。
console.log(o.f);  //my()


function c(){
  this.a = 37;
  return {a:40};//我的理解是:相当于重新给a进行赋值,值被修改为40了。
}
o = new c();
console.log(o.a);


function c(){
  this.a = 37;
  this.a = 90;
}
o = new c();
console.log(o.a);

  还有一篇关于this的链接:http://segmentfault.com/a/1190000000638443,这个写得比较好,具体内容如下:

前段时间回答的一个关于this的问题,便总结记录下。
在javascript的函数中,除了声明时定义的形参之外,每个函数还可以接收两个附加的参数:this和arguments。这里就讲一下this的作用以及不同场景下它的不同指向。this的取值(即它的指向取决于调用的模式),在javascript中明确this指向大致有四种情况:

1.函数调用模式的时候,this指向window

function aa(){
  console.log(this)
}
aa()                 //window
2.方法调用模式的时候,this指向方法所在的对象

var a={};
a.name = 'hello';
a.getName = function(){
  console.log(this.name)
}
a.getName()         //'hello'
3.构造函数模式的时候,this指向新生成的实例

function Aaa(name){
  this.name= name;
  this.getName=function(){
    console.log(this.name)
  }
}
var a = new Aaa('kitty');
a.getName()        //  'kitty'
var b = new Aaa('bobo');
b.getName()        //  'bobo'
4.apply/call调用模式的时候,this指向apply/call方法中的第一个参数

var list1 = {name:'andy'}
var list2 = {name:'peter'}

function d(){
  console.log(this.name)
}
d.call(list1)     //  'andy' 
d.call(list2)     //  'peter' 

  

posted @ 2015-04-30 16:41  Sunor  阅读(184)  评论(0编辑  收藏  举报