简体   繁体   中英

Modernizr and Video.h264

I am looking at how Modernizr detects support for Video and H.264 , but it does not make any sense to me. Isn't bool a primitive boolean? why does it become a Boolean object? Why does bool.h264 magically start making any sense at all? thanks

tests['video'] = function() {
        var elem = document.createElement('video'),
            bool = false;

        // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224
        try {
            if ( bool = !!elem.canPlayType ) {
                bool      = new Boolean(bool);
                bool.ogg  = elem.canPlayType('video/ogg; codecs="theora"')      .replace(/^no$/,'');

                // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546
                bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,'');

                bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,'');
            }

        } catch(e) { }

        return bool;
    };

Initially bool is indeed a primitive boolean, which cannot have properties added to it. Following the if condition, the value of bool gets overwritten via new Boolean(bool) . In Javascript, calling new on a function, creates an empty Object, and uses the function as a constructor for said object. In the case of the Boolean() constructor, the only notable addition to the object, is a valueOf() function which returns the original primitive value. Otherwise, you now have a normal Object which can have arbitrary properties added to it.

See here and here .

I actually wrote a majority of that test.

That is just the format that Modernizr has followed for detects with sub values. In JavaScript, everything is an object, and new Boolean is as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM