The following code:
var r = /^[0-9A-Z]$/.test;
r("A")
Throws ‘TypeError: can’t convert undefined to object’
How else could I assign the test function to a variable, for passing in functions, later evaluation, etc.? (Without wrapping the regex in another function)
Update:
Consider this bit of valid code before answering:
var o = { f: function() { return 1 } };
var a = o.f;
var b = a(); // b = 1
It has to do with the value of
thisinside thetestmethod.For example:
If you call the
testmethod “as a function” -as your exampler();-, thethisvalue will refer toundefined(for built-in or strict functions in ECMAScript 5, in the above examplethiswill refer to the global object).Calling any method of
RegExp.prototypewith athisvalue that is not aRegExpobject, will always generate thisTypeErrorexception, quoting the spec:15.10.6 Properties of the RegExp Prototype Object
However you could bind the
testmethod to yourrfunction, using theFunction.prototype.bindmethod:Or using
callorapply: