Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new 关键字的实现和原理 #3

Open
xiaochengzi6 opened this issue May 19, 2022 · 0 comments
Open

new 关键字的实现和原理 #3

xiaochengzi6 opened this issue May 19, 2022 · 0 comments
Labels
JavaScript JavaScript 语言的学习
Projects

Comments

@xiaochengzi6
Copy link
Owner

xiaochengzi6 commented May 19, 2022

new 操作符

一句话介绍 new:

new 运算符创建一个用户定义的对象类型的实例具有构造函数的内置对象类型之一

JavaScript高级程序设计(第4版)中可以看到new的工作流程

new操作执行时会做出以下操作

  1. 在内存中创建一个新对象。
  2. 这个新对象内部的[[Prototype]]特性被赋值为构造函数的 prototype 属性。
  3. 构造函数内部的 this 被赋值为这个新对象(即 this 指向新对象)。
  4. 执行构造函数内部的代码(给新对象添加属性)。
  5. 如果构造函数返回非空对象,则返回该对象;否则,返回刚创建的新对象。
  • 如果构造函数的返回值是值类型,那么就丢弃掉,依然返回构造函数创建的实例。
  • 如果构造函数的返回值是引用类型,那么就返回这个引用类型,丢弃构造函数创建的实例。

手动实践一个:

var F_new = function (obj) {
    //1.
    var o = {}
    //2.
    o._proto_ = obj.prototype
    //3. 4.
    var newobj = obj.apply(o, Array.prototype.slice.call(arguments,1))
    // 5.
   if( (typeof obj === 'object' && typeof obj !== 'null') || typeof obj === 'function'){
       return newobj
   }
    return o
}

优化一下:

var F_new = function (obj) {
  var o = Object.create(obj.prototype);
  var argArr = [].slice.call(arguments, 1);
  var newobj = obj.apply(o,argArr);
  if( (typeof newobj === 'object' && typeof newobj !== 'null') || typeof newobj === 'function'){
     return newobj
 }
  return o
}

其他版本:

const createNew = (obj,...arg) => {
    const instan = Object.create(obj.prototype);
    obj.call(instan, ...arg);
    return instan;
}

参考

JavaScript 深入之 new 的模拟实现

JS 的 new 到底是干什么的?

@xiaochengzi6 xiaochengzi6 added the JavaScript JavaScript 语言的学习 label May 19, 2022
@xiaochengzi6 xiaochengzi6 added this to 原生 API 实现 in JavaScript May 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript JavaScript 语言的学习
Projects
JavaScript
原生 API 实现
Development

No branches or pull requests

1 participant