手写

189 阅读1分钟

手写new

function myNew(calssN,...arg){
    var obj = {};
    obj.__proto__ = classN.prototype;
    var res = classN.call(obj,...arg);
    return typeof res === 'object' ? res : obj;
}
var p = myNew(classN,1)

手写instanceof

function myInstance(temp,classN){
    //temp通过__proto__向上查的时候,如有某次的__proto__ === classN.prototype 返回true
    //当某次的__ptoto__ === null  这时返回false
    Let str = typeof temp;
    if(str !== 'object' && str !=='function')return false //不是对象,也不是函数,就证明是值类型,这时return false
    var left = temp.__proto__;
    var right = classN.prototype;
    while(left){
        if(left === right)return true;
        left = left.__proto__;
    }
    return false
}

实现一个判断数据类型的方法 getType()

Object.prototype.getType = function(temp){
    let str = this.constructor.toString();
    str = str.slice(9,str.indexOf('(').toLowerCase();
    return str
}

pop push 返回值是改变的原数组

var ary = [1,2,3,4,5];
Array.prototype.myPop = function(){
    this.length--;
    return this
}
Array.prototype.myPush = functioni(...ary){
    var len = ary.length;
    for(var i = 0;i<len;i++){
        this[this.length] = ary[i];
    }
    return this
}

reverse

Array.prototype.myReverse = function(){
    for(var i = 0;i<this.length/2;i++){//循环数组长度的一半,因为一半的时候就换完了,之后再换又换回去了
        var temp = this[i];
        this[i] = this[this.length-1-i];
        this[this.length-1-i] = tem;
    }
    renturn this
}

去重

面试可以用 简单
Array.prototype.myUnique = function(){
    var arr = [...(new Set(this))];
    this.length = 0;
    this.push(...arr)
    return this
}

Array.prototype.myUnique = function(){
    var obj = {};
    for(var i = 0;i<this.length;i++){
        var temp = this[i];
        if(obj.hasOwnProperty(temp)){
            this.splice(i,1)
            i-- //小心数组塌陷
        }else{
            obj[temp] = temp;
        }
    }
}