Object methods assigned to variables or function arguments fail when invoked

后端 未结 5 939
爱一瞬间的悲伤
爱一瞬间的悲伤 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

    If you store just a method, it does not carry with it a reference to your object - it just stores a reference to the .test method, but no particular object. Remember, a method is "just" a property on an object and storing a reference to a method doesn't bind it to that object, it just stores a reference to the method.

    To invoke that method on a particular object, you have to call it with that object.

    You can make your own function that calls the method on the desired object like this:

    var v1 = function(x) {
        return /[abc]/.test(x);
    }
    

    Then, when you do this:

    v1('a');
    

    It will execute the equivalent of this in your function:

    /[abc]/.test('a');
    

    But, it isn't entirely clear why you're doing that as you could also just define the regex and call .test() on it several times:

    var myRegex = /[abc]/;
    console.log(myRegex.test('a'));
    console.log(myRegex.test('b'));
    console.log(myRegex.test('z'));
    

提交回复
热议问题