前端手写代码之JS篇[不定时更新]

253 阅读1分钟

_ proto _ 原理

Object.defineProperty(Object.prototype, '__proto__', {
    get() {
        return Object.getPrototypeOf(this)
    },
    set(o) {
        Object.setPrototypeOf(this, o)
        return o
    }
})

bind()原理

Function.prototype.bind = function() {
    let self = this //保存原函数
    let context = [].shift.apply(arguments) // 保存this指向
    let ortherArgs = [].slice.apply(arguments) //剩余参数转换成数组
    return function(...args) {
        return self.apply(context, [...ortherArgs, ...args])
    }
}
let obj = {
    a: 'a'
}

function fun(a, b) {
    console.log(this.a, a, b)
}
let example = fun.bind(obj, 'a')
example('b')

模拟new实现

function mockNew() {
    let Constructor = [].shift.call(arguments)
    let obj = {}
    obj.__proto__ = Constructor.prototype
    let r = Constructor.apply(obj, arguments)
    return r instanceof Object ? r : obj
}
let animal = mockNew(Animal, '哺乳类')
console.log(animal)

instaceof 判断原始类型

class PrimitiveString {
    static [Symbol.hasInstance](x) {
        return typeof x === 'string'
    }
}
console.log('hello world' instanceof PrimitiveString)  // true