[js高手之路]this知多少

时间:2023-03-09 07:14:48
[js高手之路]this知多少

this关键字在javascript中的变化非常的灵活,如果用的不好就非常恶心,用的好,程序就非常的优雅,灵活,飘逸.所以掌握this的用法,是每一个前端工程师必知必会的.而且这个也是一些大公司笔试中常见的考察项.

第一种、单独的this,指向的是window这个对象

console.log( this ); //window
注:当前的执行环境是window, 所以this指向了window
第二种、全局函数中的this
         function show(){
alert( this ); //window
}
show();

show()这样子调用,指向的是window

第三种、函数调用的时候,前面加上new关键字,也就是构造函数的调用方式

     function show(){
alert( this ); //object
}
new show();

new show这样调用,函数中的this指向的是object

第四种、用call与apply的方式调用函数,这里面的this分两种情况

  • 一般情况下,call与apply后面的第一个参数, 该参数是什么, this就指向什么
  • call与apply后面如果是undefined和null,this指向的是window
         function show(){
alert( this ); //abc
}
show.call('abc'); //abc
          function show(){
alert( this );
}
show.call( null ); //window
show.call( undefined ); //window
show.call( '' ); //''
         function show( a, b ){
alert( this + '\n' + a + ',' + b ); //abc, ghostwu, 22
}
show.call( "abc", 'ghostwu', 22 );
show.apply( "abc", ['ghostwu', 22] );
 function show( a, b ){
alert( this + '\n' + a + ',' + b );
}
show.call( "abc", 'ghostwu', 22 ); //abc, ghostwu, 22
show.apply( null, ['ghostwu', 22] ); //window, ghostwu, 22
show.apply( undefined, ['ghostwu', 22] );// window, ghostwu, 22

这里要稍微注意一下, call与apply后面的参数传递的区别: call是一个个把参数传递给函数的参数,而apply是把参数当做数组传递给函数的参数,数组第一项传递给函数的第一个参数,第二项传递给函数的第二个参数。。。以此类推

第五种、定时器中的this,指向的是window

      setTimeout( function(){
alert( this ); //window
}, 500 );

第六种、元素绑定事件,事件触发后 执行的函数中的this 指向的是当前的元素

 <input type="button" value="点我">
<script>
document.querySelector("input").onclick = function(){
alert(this); //指向当前按钮
};
</script>

第七种、函数调用时如果绑定了bind, 那么函数中的this就指向了bind中绑定的东西

 <input type="button" value="点我">
document.querySelector("input").addEventListener("click", function(){
alert(this); //window
}.bind(window));

如果没有通过bind改变this,那么this的指向就会跟第六种情况一样

第八种、对象中的方法:该方法被哪个对象调用,那么方法中的this就指向该对象

        var obj = {
userName : "ghostwu",
show : function(){
return this.userName;
}
};
alert( obj.show() ); //ghostwu

如果把对象的方法,赋给一个全局变量,然后再调用,那么this指向的就是window.

         var obj = {
userName : "ghostwu",
show : function(){
return this.userName;
}
};
var fn = obj.show;
var userName = 'hello';
alert( fn() );// hello, this指向window

学完之后,我们就来应用下,下面这道题是腾讯考察this的面试题,你都能做出来吗?

         var x = 20;
var a = {
x: 15,
fn: function () {
var x = 30;
return function () {
return this.x;
};
}
};
console.log(a.fn()); //function(){return this.x}
console.log((a.fn())()); //
console.log(a.fn()()); //
console.log(a.fn()() == (a.fn())()); //true
console.log(a.fn().call(this)); //
console.log(a.fn().call(a)); //

你如果真的搞懂了this,面向对象水平也不错的话,可以来试试,我的博客中这道腾讯的面试题额:

学生问的一道javascript面试题[来自腾讯]