zoukankan      html  css  js  c++  java
  • JS 实现new 关键字

    首先要清楚类和对象之间的关系,然后要清楚实例化(new)的过程中发生了什么。

    笔者认为类和对象的关系比较好理解,就如同要按照图纸盖一幢房子,图纸就是类,房子就是对象。类是对象的抽象,对象是类的实体体现。

    new的过程发生了什么呢?

    var Person=function(name,age){
        this.name=name;
        this.age=age;
    }
    Person.prototype.getName=function(){
        return this.name;
    }
    var p1=new Person('Tom',12)
    p1.getName()    //Tom

    有上面的例子可知,new的过程中创建了一个对象,根据构造函数的结构,原型,及方法等全部赋给这个对象,最后返回这个对象。

    实现代码如下:

    function New(fn){
        var res = {};
        if(fn.prototype !== null) {
            res.__proto__=fn.prototype;
        }
        // 将传入构造函数的参数,在res上下文中执行一遍
        var ret = fn.apply(res,Array.prototype.slice.call(arguments,1));
        // 如果构造函数返回一个对象,则直接返回这个对象 
        if((typeof ret === 'object' || typeof ret === 'function') && ret !== null){
            return ret;
        }
        return res;
    }
    var Person = function(name,age){
        this.name=name;
        this.age=age;
    }
    Person.prototype.getName=function(){
        return this.name;
    }
    var p1=New(Person,'Tom',12)
    console.log(p1.getName())//Tom
  • 相关阅读:
    python向mysql中插入数字、字符串、日期总结
    selenium鼠标事件
    iOS hook
    网络抓包篇
    frida IOS环境搭建
    git
    $emit
    better-scroll无法滚动的问题。
    this.$nextTick()作用
    better-scroll
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/11000118.html
Copyright © 2011-2022 走看看