函数的调用和this的指向
1.普通函数调用 this 指向 window
function fn() { console.log(this); } window.fn();
2.方法调用 this 指向 调用该方法的对象
var obj = { fun: function () { console.log(this); } } obj.fun();
3.作为构造函数的调用 构造函数内部的this指向由该构造函数创建的对象
var gf = { name : "tangwei", bar : "c++", sayWhat : function() { console.log(this.name + "said:love you forever"); } }
4.作为事件的处理函数 触发该事件的对象
btn.onclick = function () { console.log(this); }
5.作为定时器的参数 this 指向 window
setInterval(function() { console.log(this); }, 1000);
总结:函数内部的this,是由函数调用的时候来确定其指向的。
本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript教程视频栏目!
以上就是JavaScript中函数的调用和this的指向介绍(代码)的详细内容,更多请关注php中文网其它相关文章!