JS手写系列

138 阅读2分钟

split

  实现JSStringAPIsplit\color{#4285f4}{实现JS中String的API,split}

       var str = "fontSize:14px";
       function splitFuntion(str, flag) {
           let tempArr = [], prev = 0,tempStr;
           for (let i = 0; i < str.length; ++i) {
                if (str[i] === flag) {
                    tempStr = str.substring(prev, i);
                    tempArr.push(tempStr);
                    prev = i + 1;
                }
           }
           if(prev < str.length){
                tempStr = str.substring(prev, str.length)
                tempArr.push(tempStr)
           }
       }
       splitFuntion(str, ":")

join

  实现JS中数组的joinjoin\color{#4285f4}{实现JS中数组的join,join}

const elements = ['Fire', 'Air', 'Water'];
        function join(el,flag){
            let str = ""
            for(let i = 0; i < el.length; i++){
                str += el[i] + flag;
            }
            return str.substring(0,str.length - flag.length)
        }
        let a = join(elements,",")
        console.log(a,"---****---")

new

  实现JSnew方法\color{#4285f4}{实现JS中new方法}

        function FakeNew(){
            //创建新对象
            var obj = Object.create(null);
            //拿到这个函数
            var ConstructorFun = [].shift.call(arguments);
            //让这个函数的prototype指向obj.__proto__
            obj.__proto__ = ConstructorFun.prototype;
            //将函数内部的this赋值给新的对象
            var ret = ConstructorFun.apply(obj,arguments);
            //如果构造函数返回非空对象,则返回该对象。否则返回 this。
            return (typeof ret === 'object' && ret !== null) || typeof ret === "function" ? ret : obj;
        }
        function Person(name,age){
            this.name = name;
            this.age = age;
        }
        var obj = FakeNew(Person,'jack',18)
        console.log(obj)

call

  实现JScall方法\color{#4285f4}{实现JS中call方法}

         Function.prototype.call = function (thisArg, ...argsArray) {
            if (typeof this !== 'function') {
                throw new TypeError(
                    "Function.prototype.call was called on which is not a function"
                );
            }
            if (thisArg === undefined || thisArg === null) {
                thisArg = window;
            } else {
                thisArg = Object(thisArg)
            }
            const func = Symbol("func");
            thisArg[func] = this;
            let result;
            if (argsArray.length) {
                result = thisArg[func](...argsArray);
            } else {
                result = thisArg[func]();
            }
            delete thisArg[func];
            return result;
        }
        var person = {
            fullName: function () {
                return this.firstName + " " + this.lastName
            }
        }
        var person1 = {
            firstName: "jack",
            lastName: "jack1"
        }
        let a = person.fullName.call(person1)
        console.log(a)

apply

  实现JSapply方法\color{#4285f4}{实现JS中apply方法}

        Function.prototype.apply = function(thisArgs,args){
            if(typeof this !== "function"){
                throw new Error('Function.prototype.apply must be a function!')
            }
            if(thisArgs === null || thisArgs === undefined){
                thisArgs = window;
            }else{
                thisArgs = Object(thisArgs)
            }
            const func = Symbol("func");
            thisArgs[sync] = this;
            let result;

            if(typeof args === 'object' && length in args){
                result = thisArgs[func](...Array.from(args))
            }else if(argsArray === undefined || argsArray === null){
                result = thisArgs[func](args)
            }else{
                throw new Error("CreateListFromArrayLike called on non-object")
            }
            delete thisArgs[sync];
            return result;
        }

        var peroson = {
            name: "华哥",
            age: 18,
            doSomething: function (time) {
                return this.name + this.age + "***" + time;
            }
        }
        var person1 = {
            name: "jack",
            age: 20
        }
        console.log(peroson.doSomething.apply(person1, ["15"]))

bind

  实现JSbind方法\color{#4285f4}{实现JS中bind方法}

     Function.prototype.bind = function (thisArg, ...arg) {
            if (typeof this !== 'function') {
                throw new Error("Function.prototype.bind must be a function")
            }
            if (thisArg === null || thisArg === undefined) {
                thisArg = window;
            } else {
                thisArg = Object(thisArg);
            }
            const func = this;
            const bound = function (...boundArgsArray) {
                let isNew = false;
                try {
                    isNew = this instanceof func;
                } catch (e) {}
                return func.apply(isNew ? this : thisArg, arg.concat(boundArgsArray));
            }
            const Empty = function () { };
            Empty.prototype = this.prototype;
            bound.prototype = new Empty();
            return bound;
        }
        var name = "小王",age = 17;
        var obj = {
            name:"小张",
            objAge:this.age,
            myFun:function(){
                console.log(this.name + "年龄" + this.age)
            }
        }
        var db ={
            name:"德玛",
            age:99
        }
        obj.myFun.bind(db)()

instanceof

  实现JSinstanceof方法\color{#4285f4}{实现JS中instanceof方法}

    function Person(name, age) {
            this.name = name;
            this.age = age;
    }
    function myInstanceOf(L, R) {
            if (typeof L === null || typeof L !== "object") return false;
            let proto = Object.getPrototypeOf(L)
            while (true) {
                if (proto == null) return false;
                //找到相同的原型对象
                if (proto == R.prototype) return true;
                proto = Object.getPrototypeOf(proto);
           }
    }
    let a = myInstanceOf(p1, Person)
    console.log(a)

检测对象数组的每一项是否为空,如果为空,那么返回那一项的键名,如果不为空,则返回true

  实现JS中检测对象数组的每一项是否为空\color{#4285f4}{实现JS中检测对象数组的每一项是否为空}

        function checkObjectArray(...objArr) {
            for (let i = 0; i < objArr.length; i++) {
                for (let key in objArr[i]) {
                    if (!objArr[i][key]) {
                        return `${key}不能为空!`;
                    }
                }
            }
            return true;
        }
        var a = {
            b: 1,
            c: "21",
            d: 2,
            f:1,
            g:""
        }
        let result = checkObjectArray(a);
        console.log(result)