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
- 【javascript】javascript中的this
- JavaScript中的this指针
- javascript 中的"this"
- javascript中的this!
- Javascript中的this讲解
- Javascript中的this关键字
- javascript中的this
- JavaScript中的this关键字
- JavaScript中的this详解
- JavaScript中的this指针
- javascript中的this
- JavaScript 中的this 关键字
- 有关javascript中的this
- javascript中的this
- JavaScript 中的 this
- Javascript中的this
- javascript中的this
- JavaScript中的this用法
- 【状态压缩DP】uva11825Hackers' Crackdown
- 系统上线后关键用户的工作建议
- java之顶级父类Object
- url注意事项
- Lucene一(开篇:lucene整体学习路线和初体验)
- javascript中的this
- 查看C++类的虚表(vtable)结构
- I - Faulty Odometer
- Hibernate中根据实体查询报错Ljava.lang.Object; cannot be。。。
- sdnu 1031 字母排序(拓扑排序的利用)
- 关于register修饰符以及在C 与 C++中的区别
- D - Game with Pearls
- 7/21 A 解题报告
- HDOJ_Problem Archive_1000_A + B Problem