前端原生函数js 实现

153 阅读2分钟
# JS 数组原生内置函数的实现
## forEach
Array.prototype.myforEach = function (callback, thisarg) {
    if (typeof this === 'undefined' || this === null) {
        throw new TypeError('this is null or not defined')
    } else if (typeof callback !== 'function') {
        throw new TypeError(callback + ' is not a function')
    } else {
        var i = 0
        var len = this.length >>> 0
        var arr = Object(this)
        while (len > i) {
            if (i in arr) {
                callback.call(thisarg, arr[i], i, arr)
            }
            i++
        }
    }
}

## map
Array.prototype.mymap = function (callback, thisarg) {
    if (typeof this === 'undefined' || this === null) {
        throw new TypeError('this is null or not defined')
    } else if (typeof callback !== 'function') {
        throw new TypeError(callback + ' is not a function')
    } else {
        var i = 0
        var len = this.length >>> 0
        var arr = Object(this)
        var res = []
        while (len > i) {
            if (i in arr) {
                res[i] = callback.call(thisarg, arr[i], i, arr)
            }
            i++
        }
        return res
    }
}

## filter
Array.prototype.myfilter = function (callback, thisarg) {
    if (typeof this === 'undefined' || this === null) {
        throw new TypeError('this is null or not defined')
    } else if (typeof callback !== 'function') {
        throw new TypeError(callback + ' is not a function')
    } else {
        var i = 0
        var len = this.length >>> 0
        var arr = Object(this)
        var res = []
        while (len > i) {
            if (i in arr) {
                callback.call(thisarg, arr[i], i, arr) && res.push(arr[i])
            }
            i++
        }
        return res
    }
}

## some
Array.prototype.mysome = function (callback, thisarg) {
    if (typeof this === 'undefined' || this === null) {
        throw new TypeError('this is null or not defined')
    } else if (typeof callback !== 'function') {
        throw new TypeError(callback + ' is not a function')
    } else {
        var i = 0
        var len = this.length >>> 0
        var arr = Object(this)
        while (len > i) {
            if (i in arr) {
                if (callback.call(thisarg, arr[i], i, arr))
                    return true
            }
            i++
        }
        return false
    }
}

## reduce
Array.prototype.myreduce = function (callback, defaultValue) {
    if (typeof this === 'undefined' || this === null) {
        throw new TypeError('this is null or not defined')
    } else if (typeof callback !== 'function') {
        throw new TypeError(callback + ' is not a function')
    } else {
        var i = 0
        var len = this.length >>> 0
        var arr = Object(this)
        var count = defaultValue || arr[i++] // 如果没有初始值 则取数组第一个非空的值 循环从下一个数组项开始
        while (len > i) {
            if (i in arr) {
                count = callback(count, arr[i], i, arr)
            }
            i++
        }
        return count
    }
}

## 自定义数组去重(简写版)
Array.prototype.removeRepeat = function () {
    if (this instanceof Array) {
        var arr = this
        var len = arr.length
        for (var i = 0; i < len; i++) {
            for (var j = i + 1; j < len; j++) {
                if (arr[i] === arr[j]) {
                    arr.splice(j, 1)
                    len--
                    j--
                }
            }
        }
        return arr
    } else {
        throw new TypeError(this + ' is not a Array')
    }
}

# 改变this 指向的 call,apply,bind
## call
Function.prototype.mycall = function (context, ...arg) {
    context = context || window
    context.fn = this
    var res = context.fn(...arg)
    delete context.fn
    return res
}
Function.prototype.mycall2 = function (context) {
    context = context || window
    context.fn = this
    var len = arguments.length
    var i = 1
    var arg = []
    while (i < len) {
        arg.push(arguments[i++])
    }
    var res = eval('context.fn(' + arg + ')')
    delete context.fn
    return res
}

## apply
Function.prototype.myapply = function (context, arg) {
    var context = context || window
    context.fn = this
    var res = eval('context.fn(' + arg + ')')
    delete context.fn
    return res
}

## bind
Function.prototype.mybind = function () {
    var context = window
    var len = arguments.length
    if (len > 0) {
        context = arguments[0]
    }
    context.fn = this
    var i = 1
    var args = [] // [].slice.call(arguments, 1)
    while (i < len) {
        args.push(arguments[i++])
    }
    return function () {
        var res = eval('context.fn(' + args + ')')
        delete context.fn
        return res
    }
}

# Object 内置函数
## Object.create
Object.myCreate = function (proto, propertyObject = undefined) {
    if (typeof proto !== 'object' && typeof proto !== 'function') {
        throw new TypeError('Object prototype may only be an Object or null.')
    }
    if (propertyObject == null) {
        new TypeError('Cannot convert undefined or null to object')
    }
    function fn () {}
    fn.prototype = proto
    const f = new fn()
    if (propertyObject != undefined) {
        Object.defineProperties(f, propertyObject)
    }
    if (proto === null) {
        f.__proto__ = null
    }
    return f
}

## Object.assign
Object.myAssign = function (target, ...source) {
    if (target == null) {
        throw new TypeError('cannot convert undefined or null to object')
    }
    let obj = Object(target)
    source.forEach(item => {
        if (item != null) {
            for (let key in item) {
                if (item.hasOwnProperty(key)) {
                    obj[key] = item[key]
                }
            }
        }
    })
    return obj
}

# 其它
## new
function mynew() {
    var obj = new Object()
    var constructor = [].shift.call(arguments)
    obj.__proto__ = constructor.prototype
    var ret = constructor.apply(obj, arguments)
    return typeof ret === 'object' ? ret || obj : obj
}

## instanceof
function myInstanceof(leftobj, rightobj) {
    return leftobj.__proto__ === rightobj.prototype
}

## JSON.parse
JSON.myParse = function (jsonstr) {
    return (new Function('return ' + jsonstr))();
}

--- 写的有问题的地方欢迎指出