js的this关键字
来源:互联网 发布:数据精灵源 编辑:程序博客网 时间:2024/05/17 08:29
this是一个引用。下面有5种this的变化情况:
1.在函数运行时,每个函数都有一个调用它的上下文,而这个this就是指向这个上下文对象。
example:
var test = function(){console.log(this);}test();//输出window对象var test = function(){var attr1 = 'hello';console.log(this);console.log(this.attr1);}test();//输出window对象和undefined//Temp构造函数var Temp = function (attr1,func){this.attr1 = attr1;this.test = func;}var temp = new Temp("world",test);temp.test();//输出Temp对象和world
2.在构造函数里this指向该函数创建的实例对象的引用,对象Object里this指向该对象引用,我们就可以轻易在该这些对象里调用自己的方法和属性。
example:
//这是test构造函数var Test = function (attr1, attr2){this.attr1 = attr1;this.attr2 = attr2;this.func = function(){console.log(this);//Test创建的对象实例console.log(this.attr1);//attr1的值console.log(Test.attr1);//undefined}};//这是object对象var object = {attr1 : 'hello ',attr2 : 'world',func : function (){console.log(this);//object对象console.log(this.attr1);//helloconsole.log(object.attr1);//hello}}var temp = new Test('hello', 'world');temp.func();//输出Test对象 ,hello, undefinedobject.func();//输出object对象, hello, hello
example:
var Test = function (attr1, attr2){this.attr1 = attr1;this.attr2 = attr2;this.func = function(){console.log(this);//Test创建的对象实例var inner = (function(){console.log(this);//window对象})();}};//这是object对象var object = {attr1 : 'hello ',attr2 : 'world',func : function (){console.log(this);//object对象var inner = (function(){console.log(this);//window对象})();}}var temp = new Test('hello', 'world');temp.func();//输出Test对象实例 ,hello, undefinedobject.func();//输出object对象, hello, hello
4.事件函数,this指向触发的元素。
example:
<!doctype html><html><head><title>Test</title><script>window.onload = funciton(){document.getElementById('test').onclick=function(){console.log(this);//输出触发的button对象};}</script></head><body><button id="test'>click me!</button></body></html>
5.call和apply方法可以改变函数的this。在调用call和apply方法时,传入要this指向的对象。
example:
var test = function(){console.log(this);console.log(this.attr1);}var object = {attr1 : 'hello',attr2 : 'world'}test();//window对象,undefined, [from window]test.call(object,null);//object对象,hello ,["this ", "is ", "call"] test.apply(object,null);//object对象,hello,["this ", "is ", "apply"]
call和apply的区别是:call只能一个一个参数传入,而apply传入的是数组。
0 0
- JS的this关键字
- JS的this关键字
- js的this关键字
- JS的this关键字
- JS:this关键字的指向
- js中this关键字的使用
- JS中this关键字的使用
- 详解js里的this关键字
- js中this关键字的用法
- JS 中 和 JQuery 的 this 关键字
- js中this关键字的指向问题
- js中对this关键字的理解
- JS中this关键字的区别
- JS函数的 this 关键字详解
- js中关于this关键字的理解
- js中this关键字的指向
- js中的this关键字
- JS This关键字
- 成大资工Xenomai相关wiki
- VM上的Redhat Linux共享Windows文件夹
- 发现C++Builder 2010集合类的一个BUG
- keepalived配置及典型应用案例
- C语言字节对齐详解
- js的this关键字
- OWLAI
- linux中rpm常用命令
- UVa 489 Hangman Judge 刽子手游戏
- 黑马程序员——黑马学习日志之八 异常
- 编译qemu时添加选项
- tcp连接的11种状态
- 单点登录
- php——学习笔记 设置背景和段落以及段落样式