手写js

49 阅读2分钟

1.instanceof

  • instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
  • Array.prototype.includes()

includes()  方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false

  • Object.getPrototypeOf()

Object.getPrototypeOf()  静态方法返回指定对象的原型(即内部 [[Prototype]] 属性的值)。

// 递归
function _instanceof(obj, func) {
    if(!(obj && ['object', 'function'].includes(typeof obj))) {
        return false
    }

    let proto = Object.getPrototypeOf(obj)
    if(proto === func.prototype) {
        return true
    } else if(proto === null) {
        return false
    } else {
        return _instanceof(proto, func)
    }
}

//遍历
function _instanceof_1(obj, func) {
    if(!(obj && ['object', 'function'].includes(typeof obj))) {
        return false
    }
    let proto;
    while(proto = Object.getPrototypeOf(obj)) {
        if(proto === func.prototype) {
            return true
        }
    }

    return false
}


2. Array.prototype.reduce()

reduce()  方法对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。否则,数组索引为 0 的元素将被用作初始值,迭代器将从第二个元素开始执行(即从索引为 1 而不是 0 的位置开始)。

Array.prototype._reduce = function(callback, initValue) {
    if(typeof callback  !== 'function') {
        throw new Error(`${callback} is not a function`)
    }

    let index = 0;
    let result;

    if(!initValue) {
        result = this[0]
        index = 1;
    }

    for(let i = index; i < this.length; i++) {
        result = callback(result, this[i], i. this)
    }
    return result
}

3. new

Object.create()

Object.create()  静态方法以一个现有对象作为原型,创建一个新对象。

  • 创建一个新对象
  • 将新对象的原型指向构造函数的原型
  • 调用构造函数,并将this指向新对象(为对象初始化或赋值)
  • 返回新对象
function _new(func, args) {
    const obj = Object.create(func.prototype)
    const result = func.apply(obj, args);
    if(typeof result === 'object' && result !== null || typeof result === 'function') {
        return result
    } else {
        return obj
    }
}