Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
794 views
in Technique[技术] by (71.8m points)

javascript - Object methods assigned to variables or function arguments fail when invoked

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 this one out:

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

says test method called on incompatible undefined, I'm trying to store the test method of that regex into variable and invoke it later.

but it works with my own functions:

function foo(){
    return 'I'm foo';
}

var f = foo;
f(); // returns I'm foo

It should work on methods too, since functions are just methods of parent object anyway, right?

Ultimately, the reason I'm trying this is to be able to write something like this:

var a = ['a', 'b', 'c'];
a.every( (/[abc]/).test );

to check each array member against that regex.

Why doesn't this work? Is it limitation in passing built-in functions around? Or am I just doing something wrong?

PS: If you grind your teeth now and muffling something about bad practices, screw good practices, I'm just playing. But I'd like to hear about them too.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...