Why is this vali开发者_StackOverflow社区d:
function func(a,b,c) {
console.log(this, a,b,c);
return '';
}
'testing'.replace(/e/, func);
but this isn't:
function func(a,b,c) {
console.log(this, a,b,c);
return '';
}
'testing'.replace(/e/, func.call);
if func is a function reference, and call is a function reference shouldn't they both work?
Here's a fiddle of this
Because when you pass the call
function, you take it out of the context of func
, so inside call
the this
keyword will refer to window
instead of func
.
window
is not a function, but call
expects this
to be a function, so it breaks.
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);
Because .call()
itself is a method, but not one that is useful to replace()
.
In other words, while your intention is to pass func
, you're actually passing a completely different function (call
) that serves a purpose not useful as an argument to .replace()
.
精彩评论