将RegExp.test分配给一个变量 [英] Assigning RegExp.test to a variable

查看:140
本文介绍了将RegExp.test分配给一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

  var r = /^[0-9A-Z]$/.test; 
r(A)

引发'TypeError:无法将undefined转换为对象'

如何将测试函数分配给变量,用于传递函数,稍后评估等? (没有在另一个函数中包装正则表达式)

更新:

在回答之前考虑这一点有效的代码:

  var o = {f:function(){return 1}}; 
var a = o.f;
var b = a(); // b = 1


解决方案

test 方法中 this 的值。



例如:

pre $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $方法:function(){return this === obj}
};

obj.method(); // true

var method = obj.method;
method(); // false

如果您调用 test 方法作为一个函数 - 作为你的例子 r(); - , this 值将引用未定义(对于ECMAScript 5中的内置函数或严格函数,在上面的示例中, this 将引用全局对象)。

调用 RegExp.prototype 的任何方法并使用这个不是 RegExp 对象的值,将始终生成这个 TypeError 异常,引用规范:



15.10.6 RegExp原型对象的属性
$ b


在以下对RegExp原型对象属性的函数描述中,短语此RegExp对象指的是这个值用于调用该函数;如果此值不是对象或[[Class]]内部属性的值不是RegExp的对象,则会抛出TypeError异常。


然而,您可以将 test 方法绑定到 r 函数,使用 Function.prototype.bind 方法:

  var re = / ^ [0- 9A-Z] $ /,
r = re.test.bind(re);

r(A); // true

或者使用调用 apply

  var r = re.test; 
r.call(re,A); // true


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 this inside the test method.

For example:

var obj = {
  method: function () { return this === obj }
};

obj.method(); // true

var method = obj.method;
method(); // false

If you call the test method "as a function" -as your example r();-, the this value will refer to undefined (for built-in or strict functions in ECMAScript 5, in the above example this will refer to the global object).

Calling any method of RegExp.prototype with a this value that is not a RegExp object, will always generate this TypeError exception, quoting the spec:

15.10.6 Properties of the RegExp Prototype Object

In the following descriptions of functions that are properties of the RegExp prototype object, the phrase "this RegExp object" refers to the object that is the this value for the invocation of the function; a TypeError exception is thrown if the this value is not an object or an object for which the value of the [[Class]] internal property is not "RegExp".

However you could bind the test method to your r function, using the Function.prototype.bind method:

var re = /^[0-9A-Z]$/,
    r = re.test.bind(re);

r("A"); // true

Or using call or apply:

var r = re.test;
r.call(re, "A"); // true

这篇关于将RegExp.test分配给一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆