Skip to content

手写API

手写apply

js
// apply入参是数组
Function.prototype.myApply=function(obj, argArray){
    const symbol = Symbol()
    obj[symbol] = this
    obj[symbol](...(argArray || []))
    delete obj[symbol]
}

手写call

js
Function.prototype.myCall=function(obj, ...argArray){
    const symbol = Symbol()
    obj[symbol] = this
    obj[symbol](...argArray)
    delete obj[symbol]
}

手写bind

js
Function.prototype.myBind = function(obj, ...args) {
    const _self = this
    return function(...otherArgs) {
        _self.apply(obj, (args || []).concat(otherArgs || []))
    }
}

手写new

js
function myNew(Fn, ...args) {
    if (typeof Fn !== 'function') {
        throw new Error('type Error')
    }
    const newObj = {}
    newObj.__proto__ = Fn.prototype
    let res = Fn.call(newObj, ...args)
    return res ? res :newObj
}

手写Object.create

js
function create(obj) {
    function F() {}
    F.prototype = obj
    F.prototype.constructor = F
    return new F()
}

手写继承

img.png 以下几种继承写法来源《红宝书8-3继承》章节,原理就是上面的图,要是开发就用class继承。

原型链继承

js
function superType() {};
subType.prototype = new SuperType();
subType.prototype.fn = function () {};

盗用构造函数

js
function superType() {};
function subType() {
    superType.call(this)
}

组合继承

js
function superType(name) {
    this.name = name
};
function subType(name, age) {
    superType.call(this, name)
    this.age = age
}
subType.prototype = new subType()

原型式继承

js
function object(o) {
    function F() {}
    F.prototype = o
    return new F()
}
// 后来ES5 增加 object.create 将object规范化
const subObj = Object.create(superObj, {name: 'xxx'})

寄生式继承

js
function createAnthor(origin) {
    let clone = Object.create(origin)
    clone.sayHi = function () {}
    return clone
}

寄生式组合继承

引用类型继承的最佳模式

js
function inheritPrototype(subType, superType) {
    let prototype = Object.create(superType.prototype)
    prototype.constructor = subType
    subType.prototype = prototype
}

function SuperType() {}
function SubType() {}
inheritPrototype(SubType, SuperType)

类继承

js
class SubType extends SuperType() {
    constructor() {
        super();
    }
}

手写Promise

大佬完整版教程Promise A+,我就不献丑了。