Question

I see that in PHP there are functions that can accept multiple options into a single argument, for example:

error_reporting(E_ERROR & E_WARNING);

I want to implement this kind of functionality into my javascript function. Do you know examples of functions that take this kind of arguments?

I'm totally confused about how does the function know what are the options that are passed...

Was it helpful?

Solution

Yes, it's possible, but it works with |.

var flag1 = 1,
    flag2 = 2; // powers of 2

function get(flags) {
    if((flags & flag1) === flag1) { // remove all other bits and check
        alert('flag1');             // whether you get the flag itself
    }

    if((flags & flag2) === flag2) {
        alert('flag2');
    }
}

get(flag1 | flag2); // alerts both

You could of course create a helper function which does the chekcing so that you don't need those parentheses:

function contains(flags, flag) {
    return (flags & flag) === flag;
}

http://jsfiddle.net/pimvdb/NpFYj/1/

OTHER TIPS

(Assume it is instead: error_reporting(E_ERROR | E_WARNING); )

Well, it is a bitmask. So E_ERROR might be a number like this (in binary):

0010000

and E_WARNING might be:

0000010

and when they are combined with |, you get

0010010

(a single integer, with multiple bits set)

The function can then check which bits are set using the & bitwise operator. You can certainly do it in javascript, although it might be less common, and possibly less efficient and reliable as the numbers get bigger since javascript doesn't really have integers, they are really floating point numbers.

In javascript, you might prefer to use something like this:

error_reporting({warning: true, error: true});

(edited to show it in the more sensible way, with | not & to combine them)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top