• new 和 Object.create()区别


    new 和 Object.create()区别

    new操作符创建一个对象的过程

    • 创建一个对象obj
    • 将obj连接到原型链上,即设置obj.__proto__ = Constructor.prototype
    • 绑定this指向,传参执行原型函数(参数应用到obj对象上)
    • 判断执行结果,没有则返回obj
    /* 手写方法 */
    function myNew() {
        /* 创建新对象 */
        let obj = new Object();
        /* 构造函数,取第一个传入的参数,arguments不是数组,不存在shift方法 */
        let Constructor = [].shift.call(arguments);//Person
        /* 原型链 */
        obj.__proto__ = Constructor.prototype;/* obj->Person.prototype->Person */
        /* 绑定this指向传值,获取返回值 */
        let res = Constructor.apply(obj, arguments);//Person(name,age)
        /* 若结果不是对象则返回obj */
        return typeof res === 'object' ? res : obj;
    }
    

    Object.create创建一个对象的过程

    • 创造一个空构造函数
    • 将空的构造函数prototype设为传入的prototype
    • 返回实例
    Object.create = function (prototype) {
        var F = function () { };
        F.prototype = prototype;
        return new F();
    };
    

    举例:

    function A(name) {
        this.name = "AAA";
    }
    A.prototype.age = 18;
    // new
    let a1 = new A();
    console.log(a1);//A { name: 'AAA' }
    console.log(a1.age);//18
    // Object.create
    let a2 = Object.create(A.prototype);
    console.log(a2);//A {}
    console.log(a2.age);//18
    

    从执行过程和例子可以看出,newObject.create创建的的实例都具备prototype的属性和参数,但是new创建的实例执行了原来的构造函数A使新对象具备了原构造函数A自身的属性,而Object.create先创建一个空构造函数F,再进行new F()操作,原构造函数A的自身属性不被继承.

  • 相关阅读:
    python 结巴分词简介以及操作
    JWT(Json web token)简介
    为什么推荐前端使用Vue.js
    Vue 加载外部js文件
    Docker简介以及操作
    'QueryDict' object is not callable 错误解析
    django- Vue.js 操作
    django —— KindEditor
    websocket ----简介,以及demo
    python --商品评价---- 数据表结构以及理解
  • 原文地址:https://www.cnblogs.com/aeipyuan/p/12990173.html
Copyright © 2020-2023  润新知