【JS】手写系列

121 阅读1分钟

模拟对象创建过程

使用 new 来调用函数,或者说发生构造函数调用时,会自动执行下面的操作。

  1. 创建(或者说构造)一个全新的对象。
  2. 这个新对象会被执行 [[ 原型 ]] 连接。
  3. 这个新对象会绑定到函数调用的 this。
  4. 如果函数没有返回其他对象,那么 new 表达式中的函数调用会自动返回这个新对象。
function Person(name) {
    this.name = name
}

Person.prototype.getName = function () {
    return this.name
}

function objectCreate(...params) {
    let obj = new Object()
    let Constructor = {}

    Constructor = Array.prototype.shift.call(arguments)
    obj.__proto__ = Constructor.prototype
    Constructor.call(obj, ...arguments)
    return typeof obj == 'object'? obj: {}
}

let obj = objectCreate(Person,'helloworld')
console.log(obj instanceof Person) // true
console.log(Person.prototype.isPrototypeOf(obj))  // true

let per  = new Person('helloworld')
console.log(per)

手写bind

Function.prototype.bind = function(){
    let context = [].shift.call(arguments)
    let self = this;
    let args = arguments;
    return function () {
        return self.apply(context,[...args,...arguments])
    }
}

let temp = Array.prototype.concat.bind([1,3,5],7,8,9)
console.log(temp(10,12));

函数节流

var throttle = function (fn,interval) {
    var timer,  //定时器
        firstTime = true; //是否第一次调用

    return function () {
        var args = arguments,
        __me = this;
        if (firstTime){
            fn.apply(__me,args)
            return firstTime = false
        }
        if (timer){
            return false
        }
        timer = setTimeout(function () {
            clearTimeout(timer)
            timer = null
            fn.apply(__me,args)
        },interval)

    }
};

window.onresize = throttle(function () {
    console.log('resize,500ms')
},500);

递归实现深拷贝

var obj1 = [{
    name: '臧三',
    childs: ['小明', '小芳'],
    fn: function() {},
    age: undefined
}]

var obj2 = extend2(obj1)

console.log( obj2)

function extend2(data){
    if (typeof data === 'object' && data){
        let val = typeof data.length === 'number' ? [] :{}
        for(let temp in data){
            val[temp] = extend2(data[temp])
        }
        return val
    }else {
        return data
    }
}