Skip to content

Instantly share code, notes, and snippets.

@Teemwu
Last active September 16, 2021 04:14
Show Gist options
  • Save Teemwu/cdc87c6bbfc1054e4f2a06d11721af2d to your computer and use it in GitHub Desktop.
Save Teemwu/cdc87c6bbfc1054e4f2a06d11721af2d to your computer and use it in GitHub Desktop.
手写 new 操作符
'use strict';
/**
* 手写 new 操作符
* 注:暂不支持 Class 传入
* @param {*} fn 函数
* @param {...any} args 其它参数
* @returns function
*/
function _new(fn, ...args) {
// 创建拥有 fn 原型的对象
const obj = Object.create(fn.prototype);
// fn 绑定参数
const _fn = fn.apply(obj, args);
// 判断是否有返回对象
// 有:返回创建的实例
// 无:返回新建的上下文
return _fn instanceof Object ? _fn : obj;
}
// class Foo {
// constructor(a, b) {
// this.a = a;
// this.b = b;
// console.log('a', a);
// console.log('b', b);
// }
// }
function foo(params) {
this.params = params
console.log('params', params);
}
const _foo = _new(foo, '1', 2);
console.log('_foo', _foo.__proto__);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment