可能這裡有你想要的js手寫程式碼實現

時樾1998發表於2020-03-20

前方高能預警,請你做好迎戰準備,一大js手寫程式碼實現正向你襲來。

1.call

Object.prototype.myCall = function (context, ...params) {

    if (typeof this !== 'function') {

        throw TypeError('holp caller is functiom')

    }

    let fn = Symbol('fn')

    let obj = context || window

    obj[fn] = this

    let res = obj[fn](...params)

    delete obj[fn]

    return res

}

複製程式碼

2.apply

Object.prototype.myApply = function (context, params = []) {

    if (typeof this !== 'function') {

        throw TypeError('holp caller is functiom')

    }

    let fn = Symbol('fn')

    let obj = context || window

    obj[fn] = this

    let res = obj[fn](...params)

    delete obj[fn]

    return res

}
複製程式碼

3.bind

Object.prototype.myBind = function (context, ...arg) {

    if (typeof this !== 'function') {

        throw TypeError('holp caller is functiom')

    }

    let obj = context || window

    return (...arg2) => {

        this.call(obj, ...arg, ...arg2)

    }

}

複製程式碼

4.instanceOf


function instance(L, R) {

    let l = L.__proto__

    let r = R.prototype

    while (true) {

        if (l === null) return false

        if (l === r) return true

        l = l.__proto__

    }

}

複製程式碼

5.Objeact.create

function create(obj) {

    function F() { }

    F.prototype = obj

    return new F()

}

複製程式碼

6.promise


function myPromise(constructor) {

    let that = this

    this.status = 'pendding'

    this.succVal = ''

    this.errVal = ''

    function resovle(val) {

        if (that.status === 'pendding') {

            that.succVal = val

            that.status = 'resolved'

        }

    }

    function reject(val) {

        if (that.status === 'pendding') {

            that.errVal = val

            that.status = 'rejected'

        }

    }

    try {

        constructor(resovle, reject)

    } catch (error) {

        reject(error)

    }

}

myPromise.prototype.then = function (succFn, errFn) {

    let that = this

    switch (that.status) {

        case 'resolved': succFn(that.succVal)
            break

        case 'rejected': errFn(that.errVal)
            break

    }

}

複製程式碼

7.new


function myNew(context, ...params) {

   let obj = Object.create(context.prototype)

   let res = context.apply(obj, params)

   return typeof res === 'object' ? res : obj

}

複製程式碼

8.深拷貝


function deepClone(p, c) {

    for (let prop in p) {

        if (typeof p[prop] === 'object') {

            c[prop] = p[prop] instanceof Array ? [] : {}

            deepClone(p[prop], v[prop])

        } else {

            c[prop] = p[prop]

        }

    }

}

複製程式碼

9.es5繼承


function Animal(name) {

    this.name = name

}

Animal.prototype.sayName = function () {

    console.log(this.name)

}

function Dog(name, age) {

    Animal.call(this, name)

    this.age = age

}

Dog.prototype = Object.create(Animal.prototype)

Dog.prototype.constructor = "Dog"

Dog.prototype.sayAge = function () {

    console.log(this.age)

}

複製程式碼

10.二分查詢

function binarySearch(arr, start, end, value) {

    if (start > end) {
        return -1
    }

    let middle = parseInt((start + end) / 2)

    if (value < arr[middle]) {

        end = middle + 1

        return binarySearch(arr, start, end, value)

    } else if (value > arr[middle]) {

        start = middle - 1

        return binarySearch(arr, start, end, value)

    } else if (value === arr[middle]) {

        return middle

    }

}
複製程式碼

11.快排


function quickSort(arr) {

    if (arr.length <= 1) { return arr; }

    let middle = Math.floor(arr / 2)

    let value = arr.splice(middle, 1)[0]

    let left = [], right = []

    for (let i = 0; i < arr.length; i++) {

        if (arr[i] > value) {

            right.push(arr[i])

        } else if (arr[i] < value) {

            left.push(arr[i])

        }

    }

    return quickSort(left).concat([value], quickSort(right))

}

複製程式碼

12.氣泡排序

function bubbleSort(arr) {

   let len = arr.length

   let temp

   for (let i = 0; i < len; i++) {

       for (let j = i + 1; j < len; j++) {

           if (arr[i] < arr[j]) {

               temp = arr[i]

               arr[i] = arr[j]

               arr[j] = temp

           }

       }

   }

   return arr

}
複製程式碼

13.選擇排序

function selectSort(arr) {

   let len = arr.length

   let minIndex, temp

   for (let i = 0; i < len; i++) {

       minIndex = i

       for (let j = i + 1; j < len; j++) {

           if (arr[minIndex] > arr[j]) {

               minIndex = j

           }

       }

       temp = arr[minIndex]

       arr[minIndex] = arr[i]

       arr[i] = temp

   }

   return arr

}
複製程式碼

14.原生Ajax

let xhr = new XMLHttpRequest()

xhr.open(Get,'xxx.js',false)

xhr.onreadystatechange = function () {

   if (xhr.status === 200 && xhr.readyState === 4) {

       console.log(xhr.responseText)

   }

}
複製程式碼

15.訂閱釋出模式

let Observer = (function () {

    let __msg = {}

    return {

        register: function (type, fn) {
            if (typeof __msg[type] === 'undefined') {
                __msg[type] = [fn]
            } else {
                __msg[type].push(fn)
            }
        },
        dispatch: function (type, args) {
            if (!__msg[type]) return
            let len = __msg[type].length
            let params = { type, args }
            for (let i = 0; i < len; i++) {
                __msg[type][i].call(this, params)
            }
        },
        remove: function (type, fn) {
            if (__msg[type] instanceof Array) {
                let len = __msg[type].length - 1
                for (let i = len; i >= 0; i--) {
                    __msg[type][i] === fn && __msg[type].splice(i, 1)
                }
            }
        }

    }

})()
複製程式碼

16.斐波那契演算法

function fibo(n) {

    if (n === 1 || n === 2) {

        return 1

    }

    return fibo(n - 2) + fibo(n - 1)

}
複製程式碼

17.去重

function questStep(arr) {

    let key = {}

    let value = []

    arr.forEach(element => {

        if (!(element in key)) {

            key[element] = true

            value.push(element)

        }

    })

    return value

}

複製程式碼

18.防抖

let antiShake = function () {

    let timer = null

    return function () {

        timer && clearTimeout(timer)

        timer = setTimeout(() => {

            console.log('防抖成功')

            timer = null
            
        }, 2000)


    }
}
複製程式碼

19.節流

function throttle() {

    let timer = null

    return () => {

        if (!timer) {

            timer = setTimeout(() => {

                console.log('節流成功')

                timer = null

            }, 2000)

        }

    }
}
複製程式碼

20.雙向繫結

function bothwayBind(fromKey, container, obj, key) {

    Object.defineProperty(obj, key, {

        set(val) {

            fromKey.value = val

            container.innerHTML = val

        }

    })

    fromKey.onkeyup = function (e) {

        obj[key] = e.target.value
        
    }

}
複製程式碼

21.前端路由,react-router實現

點這裡

相關文章