Why can't I use .call () in the replace function?

Why is this really:

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

but this is not so:

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

if func is a function reference and the call is a function reference, shouldn't they work?

Here is the fiddle of this

+3
source share
2 answers

Because when you pass a function call, you take it out of context func, so inside the callkeyword thiswill refer to windowinstead func.

windowis not a function, but callexpects to thisbe a function, so it is interrupted.

For comparison.

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);
+6
source

.call() , , replace().

, func, (call), , .replace().

+1

Source: https://habr.com/ru/post/1791233/


All Articles