Object methods assigned to variables or function arguments fail when invoked

后端 未结 5 921
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-21 13:11

I\'m learning javascript right now, seems like beautiful functional language to me, it is wonderful move from PHP, I should have done this earlier. Although, I cannot figure

5条回答
  •  感情败类
    2020-12-21 13:57

    The test function expects this to be a regular expression. The expression /[abc]/.test gives an unbound function (it does not remember that it belongs to /[abc]/). When you invoke it like you do, this will be undefined and the function will fail.

    You can use bind to make the function remember the object it belongs to:

    var v1 = /[abc]/.test.bind(/[abc]/);
    

    or

    var v1 = RegExp.prototype.test.bind(/[abc]/);
    

提交回复
热议问题