Javascript 为什么需要绑定通过同一对象调用的阴影函数?
当我遇到以下情况时,我正在对Array.prototype执行一些不干净的操作:Javascript 为什么需要绑定通过同一对象调用的阴影函数?,javascript,Javascript,当我遇到以下情况时,我正在对Array.prototype执行一些不干净的操作: Array.prototype.hook_pop = function(callback) { var base_pop = this.pop.bind(this); //<-- this works var base_pop = this.pop; //<-- this doesn't work this.pop = function() {
Array.prototype.hook_pop = function(callback) {
var base_pop = this.pop.bind(this); //<-- this works
var base_pop = this.pop; //<-- this doesn't work
this.pop = function() {
var ret = base_pop();
callback(ret, this);
return ret;
}
}
Array.prototype.hook\u pop=函数(回调){
var base_pop=this.pop.bind(this)//
在这一行中,您将调用base_pop()
本身,而不是作为任何对象的方法。正因为如此,它的this
值并没有设置。因为这不等于this
在这个弹出函数的上下文中。该死,我刚刚完成了我的回答。嗯,事实上,抱歉-重新打开。刚刚意识到你们在摆弄一个现有对象的内部,所以它有点多余“this”应该指向从“true,但base_pop();
不调用方法”调用方法的对象。
var ret = base_pop();