JS中this学习笔记

来源:互联网 发布:电脑桌面日程安排软件 编辑:程序博客网 时间:2024/05/21 19:29

JS中的this可以是全局对象,当前对象或者任意对象,这完全取决于函数的调用方式,执行环境。
函数的调用有:作为对象方法调用,作为函数调用,作为构造函数调用,使用call或apply调用。

1.作为函数调用

function test(){    this.x = 1;    alert(this.x);  }  test(); // 1

this为全局变量

var x = 1;  function test(){    alert(this.x);  }  test(); // 1
var x = 1;  function test(){    this.x = 0;  }  test();  alert(x); //0

2.作为对象方法调用

函数可以作为某个对象的方法调用,这时this就指这个上级对象。

function test(){    alert(this.x);  }  var o = {};  o.x = 1;  o.m = test;  o.m(); // 1

3.作为构造函数 调用

就是通过这个函数生成一个新对象(object)。这是this指向这个新对象。

function test(){    this.x = 1;  }  var o = new test();  alert(o.x); // 1
var x = 2;  function test(){    this.x = 1;  }  var o = new test();  alert(x); //2  alert(o.x); //2

4.apply或call调用

apply()是函数对象的一个方法,它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。因此,this指的就是这第一个参数。

var x = 0;  function test(){    alert(this.x);  }  var o={};  o.x = 1;  o.m = test;  o.m.apply(); //0  o.m.apply(o); //1  

apply的参数为空时,默认调用全局对象。

参考blog:
THIS用法

0 0