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


3.在嵌套函数里的this在ES5规范里指定了一个值,就是window对象。即使这个函数时嵌套在构造函数或对象里,这个this也不会再指向该对象,而是指向了window对象。

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
原创粉丝点击