Why does this JavaScript code with a regex not work as I expected?
a = /\d+/.exec; 开发者_JS百科
a("hello,123")
I getting the following error:
Error: can't convert undefined to object
Why is a
returned as undefined?
a
in this case is a reference to the RegExp.prototype.exec
function itself, and is not actually bound to any regular expression. Either of these would work:
var a = /\d+/.exec('hello,123');
var rx = /\d+/,
a = rx.exec;
a.call(rx, 'hello,123');
Your undefined
is coming from an internal reference to this
from within the exec
function.
精彩评论