为什么我不能在替换函数中使用.call()?

qwe*_*ymk 2 javascript replace reference call

为什么这是有效的:

function func(a,b,c) {
    console.log(this, a,b,c);
    return '';
}
'testing'.replace(/e/, func);
Run Code Online (Sandbox Code Playgroud)

但这不是:

function func(a,b,c) {
    console.log(this, a,b,c);
    return '';
}
'testing'.replace(/e/, func.call);
Run Code Online (Sandbox Code Playgroud)

如果func是一个函数引用,并且call是函数引用,那么它们是否都可以工作?

这里有一个小提琴的这

Que*_*tin 6

因为当你传递call功能,你把它拿出来的背景下func,这样里面callthis关键字将引用window代替func.

window不是一个函数,但call希望this是一个函数,所以它打破了.

为了比较.

var AnObject = {
    call: function () { console.log("this.location is: ", this.location); },
    location: "This string is the location property of AnObject"
};

AnObject.call();
setTimeout(AnObject.call, 500);
Run Code Online (Sandbox Code Playgroud)

  • @qwertymk - 因为它调用你传递的东西 - 并且你传递了函数,而不是函数与你从中得到它的对象. (2认同)