hgq's docs
主页
ES6-阮一峰 (opens new window)
Vue文档 (opens new window)
Axios文档 (opens new window)
Vue Router (opens new window)
Vuex文档 (opens new window)
面试题-Vue (opens new window)
面试题-JS (opens new window)

guoguoqiqi

漫不经心的向往
主页
ES6-阮一峰 (opens new window)
Vue文档 (opens new window)
Axios文档 (opens new window)
Vue Router (opens new window)
Vuex文档 (opens new window)
面试题-Vue (opens new window)
面试题-JS (opens new window)
  • call的实现
  • apply的实现
  • bind的实现
  • new的实现
    • instanceof的实现
    • Object create()的实现
    • Object assign()的实现
    • Promise的实现
    • 实现防抖函数(debounce)
    • 实现节流函数(throttle)
    • 深拷贝(deepclone)
    • 数组扁平化的实现(flat)
    • 函数柯里化
    • EventEmitter 实现
    • 数组的随机排序
    • 通用的事件侦听器函数
    • 实现一个JSONP
    • 数组的map方法
    • 数组的forEach方法
    • 数组的find方法
    • 数组的findIndex方法
    • 数组的some方法
    • 数组的filter方法
    • 数组的every方法
    • 数组的includes方法
    • 数组的fill方法
    • 数组的join方法
    • 数组的flat方法
    • 用setTimeout实现setInterval
    • 用setInterval实现setTimeout
    • 实现一个较完善的深拷贝
    • 代码手写
    guoguoqiqi
    2022-02-13

    new的实现

    # new操作符做了什么

    1. 创建了一个全新的对象。
    2. 这个对象会被执行[[Prototype]](也就是__proto__)链接。
    3. 生成的新对象会绑定到函数调用的this。
    4. 通过new创建的每个对象将最终被[[Prototype]]链接到这个函数的prototype对象上。
    5. 如果函数没有返回对象类型Object(包含Functoin, Array, Date, RegExg, Error),那么new表达式中的函数调用会自动返回这个新的对象。
    function myNew(ctor) {
    	if (typeof ctor !== "function") {
    		throw new Error("ctor must be a function");
    	}
    
    	myNew.target = ctor; // 根据ES6种new.target指向构造函数
    
    	var newObj = Object.create(ctor.prototype); // 以ctor的原型为原型创建一个新的对象
    	var argsArr = [].slice.call(arguments, 1); // 获取除ctor外后面的所有实参
    	var ctorReturnResult = ctor.apply(newObj, argsArr); // 执行构造函数,但是this绑定到newObj,为newObj赋值属性相当于
    
    	var isObject =
    		typeof ctorReturnResult === "object" && ctorReturnResult !== null;
    	var isFunction = typeof ctorReturnResult === "function";
    	if (isObject || isFunction) {
    		return ctorReturnResult;
    	}
    
    	return newObj;
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

    ← bind的实现 instanceof的实现→

    最近更新
    01
    vuex数据持久化怎么做
    05-22
    02
    vue的动态路由怎么配置使用
    05-22
    03
    vue权限控制一般怎么做
    05-22
    更多文章>
    Theme by Vdoing | Copyright © 2022-2022 Guoquoqiqi | MIT License
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式