JavaScript 中的 new 运算符是如何工作的? [英] How does the new operator work in JavaScript?

查看:29
本文介绍了JavaScript 中的 new 运算符是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是 JavaScript 中最不为人知的部分,站在原型链旁边.

Probably the least understood part of JavaScript, standing beside the prototype chain.

所以问题是:如何...

So the question is: how does...

new dataObj(args); 

...实际上创建一个对象,并定义其原型链/构造函数等?

...actually create an object, and define its prototype chain/constructors/etc?

最好是展示一个替代方案,以完全理解这个关键字.

Best is to show an alternative, to fully understand this keyword.

推荐答案

new 操作符使用内部的 [[Construct]] 方法,它基本上做了以下事情:

The new operator uses the internal [[Construct]] method, and it basically does the following:

  • 初始化一个新的本地对象
  • 设置此对象的内部[[Prototype]],指向Function prototype 属性.
    • 如果函数的 prototype 属性不是对象(原始值,例如 Number、String、Boolean、Undefined 或 Null),则使用 Object.prototype相反.
    • Initializes a new native object
    • Sets the internal [[Prototype]] of this object, pointing to the Function prototype property.
      • If the function's prototype property is not an object (a primitive values, such as a Number, String, Boolean, Undefined or Null), Object.prototype is used instead.

      new 操作符的等效实现可以这样表达(假设 ECMAScript 5 Object.create 方法可用):

      An equivalent implementation of what the new operator does, can be expressed like this (assuming that the ECMAScript 5 Object.create method is available):

      function NEW(f) {
        var obj, ret, proto;
      
        // Check if `f.prototype` is an object, not a primitive
        proto = Object(f.prototype) === f.prototype ? f.prototype : Object.prototype;
      
        // Create an object that inherits from `proto`
        obj = Object.create(proto);
      
        // Apply the function setting `obj` as the `this` value
        ret = f.apply(obj, Array.prototype.slice.call(arguments, 1));
      
        if (Object(ret) === ret) { // the result is an object?
          return ret;
        }
        return obj;
      }
      
      // Example usage:
      function Foo (arg) {
        this.prop = arg;
      }
      Foo.prototype.inherited = 'baz';
      
      var obj = NEW(Foo, 'bar');
      obj.prop;          // 'bar'
      obj.inherited;     // 'baz'
      obj instanceof Foo // true
      

      这篇关于JavaScript 中的 new 运算符是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆