js的this指针
来源:互联网 发布:回转企鹅罐 知乎 编辑:程序博客网 时间:2024/04/30 05:51
this是js的一个关键字,指向当前函数的调用对象。
1、函数调用
function test() {this.v = 1;alert(this.v);}test(); //1
this指向全局对象window
另一种形式可以证明this指向window
var v = 1;function test() {this.v = 2;}test(); //2
只要是function test(){} or test()这种形式,在函数内部,this都指向window。
eg:
test.method = function() {
function test() {
//this指向window
}
}
var test = obj.method;
test(); //函数内,this指向window而非obj。
2、作为对象方法调用
function test() {alert(this.v);}var o = {};o.v = 1;o.m = test;o.m(); //1
函数作为某个对象的方法调用的时候,this指向的是当前函数的调用对象。
经典例子(实现点击start按钮,启动计时;点击stop按钮,暂停当前计时):
涉及知识点(闭包、setInterval&setTimeout区别、this指针)。
(function() {function counter(num) {this.num = num;}; counter.prototype = { show: function() { document.getElementById('text').innerHTML = this.num++; }, start: function() { //此时this指向函数调用对象c this.stop(); var me = this; //保存当前this指向的对象c //setInterval为window对象的方法,它的第一个参数的函数在全局作用域执行,因此this指向window,要想调用show(),必须先缓存c, console.log(this === c); //true,this指向c this._timer = setInterval(function() { console.log(this === c); //false,this指向window me.show(); }, 1000); }, stop: function() { clearInterval(this._timer); }}; var c = new counter(); c.start();})();
3、作为构造函数
function test() {this.v = 1;}var o = new test();alert(o.v); //1
也就是说作为构造函数的时候,this指向的是新对象。
4、apply调用
apply( )在犀牛书里面的解释是,调用一个对象的方法,以另外一个对象替换当前对象,也就是改变当前函数的作用域。
当使用Function.prototype的call( obj, 1, 2, 3) or apply(obj, [1, 2, 3])方法时,函数的this指向函数的第一个参数,也就是obj。
var v = 1;function test() {alert(this.v);}var o = {};o.v = 2;o.m = test;o.m.apply(); //这里要注意,当apply( )参数为空的时候,默认调用window。所以这里alert出来的是1
若改为o.m.apply(o); //2
- js的this指针
- js的this指针
- js的this指针理解
- js的this指针理解
- js的this指针理解
- this指针的使用js
- js中的this指针的用法
- js中的this指针的用法
- js this指针
- js-this指针理解
- js中的this指针
- js this指针
- js之this指针
- js函数及this指针
- JS中的this指针详解
- 前端之js-this指针
- 第22篇 js中的this指针的用法
- node.js js this指针自我总结
- 如何利用蜘蛛爬行的网站
- 禅道敏捷项目管理软件的安装和使用
- 【Cocos2d-X开发学习笔记】第07期:渲染框架之摄像机类(CCCamera)的使用
- 使用CCHttpClient进行cocos2d-x网络编程
- 2013 我要不断积累 心智、技能、经验
- js的this指针
- c++初始化列表
- JDBC
- preparedment的execute报错You have an error in your SQL syntax; check the...报错问题
- @synthesize a=_a
- IAR的一个编译错误Error[e27]: Entry "GenericApp_Init::?relay" in module Coordinator
- 《程序员的第一年》---------- 消息队列与Cookie相关整理
- spring 注解模式 详解
- 指针资料整理