javascript中的this

来源:互联网 发布:北京java晚班 编辑:程序博客网 时间:2024/05/24 00:07

this对象指的是函数赖以运行的环境对象,因此this与函数的调用方式有关,函数的调用方式分为以下几种:

1.作为对象的方法调用

 var point = {  x : 0,  y : 0,  moveTo : function(x, y) {      this.x = this.x + x;      this.y = this.y + y;      }  };  point.moveTo(1, 1)//this 绑定到当前对象,即 point 对象
2.作为普通函数调用

(1)在全局作用域中调用

 function makeNoSense(x) {  this.x = x;  }  makeNoSense(5);  x;// x 已经成为一个值为 5 的全局变量

(2)调用函数内部的函数

 var point = {  x : 0,  y : 0,  moveTo : function(x, y) {      // 内部函数     var moveX = function(x) {      this.x = x;//this 绑定到了哪里?    };     // 内部函数    var moveY = function(y) {     this.y = y;//this 绑定到了哪里?    };     moveX(x);     moveY(y);     }  };  point.moveTo(1, 1);  point.x; //==>0  point.y; //==>0  x; //==>1  y; //==>1

这属于 JavaScript 的设计缺陷,正确的设计方式是内部函数的 this 应该绑定到其外层函数对应的对象上,为了规避这一设计缺陷,聪明的 JavaScript 程序员想出了变量替代的方法,约定俗成,该变量一般被命名为 that。

匿名函数的执行环境具有全局性,因此其this对象通常指向window

 var point = {  x : 0,  y : 0,  moveTo : function(x, y) {       var that = this;      // 内部函数     var moveX = function(x) {      that.x = x;      };      // 内部函数     var moveY = function(y) {      that.y = y;      }      moveX(x);      moveY(y);      }  };  point.moveTo(1, 1);  point.x; //==>1  point.y; //==>1

3.作为构造函数调用

 function Point(x, y){     this.x = x;     this.y = y;  }

4.作为事件处理程序调用

var objDiv = null ;//先理解为事件对象//1.第一种写法objDiv.onclick = function(){    //this--->objDiv }//1.第二种写法,其实这两种写法是等价的写法objDiv.onclick = show();function show(){    //this--->objDiv }


5.通过apply或call调用

 function Point(x, y){     this.x = x;     this.y = y;     this.moveTo = function(x, y){         this.x = x;         this.y = y;     }  }  var p1 = new Point(0, 0);  var p2 = {x: 0, y: 0};  p1.moveTo(1, 1);  p1.moveTo.apply(p2, [10, 10]);


 



0 0
原创粉丝点击