this总是指向函数的直接调用者(而非间接调用者)
如果有new关键字,this指向new出来的那个对象
在事件中,this指向触发这个事件的对象,特殊的是,IE中的attachEvent中的this总是指向全局对象Window
对于匿名函数或者直接调用的函数来说,this指向全局上下文(浏览器为window,NodeJS为global)
当然还有es6的箭头函数,箭头函数的指向取决于该箭头函数声明的位置,在哪里声明,this就指向哪里
this,函数执行的上下文,可以通过apply,call,bind改变this的指向。
Function.prototype.bind2 = function (context) {
if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fNOP = function () {};
var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
}
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}
参考链接:
http://blog.poetries.top/FE-Interview-Questions/base/#_70-javascript%E4%B8%ADcallee%E5%92%8Ccaller%E7%9A%84%E4%BD%9C%E7%94%A8%EF%BC%9F https://github.com/mqyqingfeng/Blog/issues/12
https://juejin.im/post/5b3c3377f265da0f8f20131f
https://juejin.im/post/59093b1fa0bb9f006517b906
原文:https://www.cnblogs.com/zxxsteven/p/11855855.html