Skip to content

Instantly share code, notes, and snippets.

@chiwent
Last active May 19, 2018 12:08
Show Gist options
  • Save chiwent/311250aa05281cc0cccbfc490a270453 to your computer and use it in GitHub Desktop.
Save chiwent/311250aa05281cc0cccbfc490a270453 to your computer and use it in GitHub Desktop.
polyfill

自己搜集的一些polyfill

原生JavaScript实现$(document).ready

function ready(fn){
    if(document.addEventListener) {
        document.addEventListener('DOMContentLoaded', function(){
            document.removeEventListener('DOMContentLoaded',arguments.callee,false);
            fn();
        },false);
    } else if(document.attachEvent) {
        document.attachEvent('onreadystatechange', function(){
            if(document.readyState == 'complete') {
                document.detachEvent('onreadystatechange', arguments.callee);
                fn();
            }
        });
    }
}

注意在严格模式下arguments.callee会报TypeError,所以为了防止报错,不要全局设置严格模式

ES5 some & every

some

demo:

function test(ele, index, arr) {
    return ele > 10;
}
var t = [3,1,2].some(test);
// false
t = [13,1,2].some(test);
// true

polyfill:

if (!Array.prototype.some) {
    Array.prototype.some = function(func) {
        'use strict';
        if (this == void 0 || this === null)
            throw new TypeError();
        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof func !== 'function')
            throw new TypeError();
        var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
        for (var i = 0; i < len; i++) {
            if (i in t && func.call(this.Arg, t[i], i, t))
                return true;
        }
        return false;
    };
}

every

demo:

function test(ele, index, arr) {
    return ele > 10;
}
var t = [1,20,3].every(test);
// false
t = [15,20,40].every(test);
// true

polyfill:

if (!Array.prototype.every) {
    Array.prototype.every = function(func) {
        'use strict';
        if (this === void 0 || this === null)
            throw new TypeError();
        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof func !== 'function')
            throw new TypeError();
        var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
        for (var i = 0; i < len; i++) {
            if (i in t && !fun.call(thisArg, t[i], i, t))
                return false;
        }
        return true;
    };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment