new 关键字在底层做了什么? [英] What does the new keyword do under the hood?

查看:27
本文介绍了new 关键字在底层做了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇 new 关键字除了改变 this 范围所指的内容之外,在后台还能做什么.

I am curious as what else the new keyword does in the background apart from changing what the this scope refers too.

例如,如果我们将使用 new 关键字使函数在对象上设置属性和方法与仅使函数返回新对象进行比较,那么新对象有什么额外的作用吗?

For example if we compare using the new keyword to make a function set properties and methods on an object to just making a function return a new object, is there anything extra that the new object does?

如果我不想从函数构造函数创建多个对象,这是首选

And which is preferred if I don't wish to create multiple objects from the function constructor

var foo2 = function () {
  var temp = "test";

  return {
    getLol: function () {
      return temp;
    },

    setLol: function(value) {
      temp = value;
    }
  };

}();

var foo = new function () {
  var temp = "test";

  this.getLol = function () {
    return temp;
  }

  this.setLol = function(value) {
    temp = value;
  }
}();

firebug profiler 告诉我使用 new 关键字稍微快一些(2ms 而不是 3ms),在大对象上 new 仍然明显更快?

The firebug profiler tells me using the new keyword is slightly faster (2ms instead of 3ms), on large objects is new still significantly faster?

另一个问题是在非常大的对象构造函数上有一个返回值在函数的底部(它将有大量的局部函数)或者在函数的顶部有一些 this.bar = ... 更多可读?什么是好的约定?

Another matter is on really large object constructors is having a return at the bottom of the function (It will have a large amount of local functions) or having a few this.bar = ... at the top of the function more readable? What is considered a good convention?

var MAIN = newfunction() {
    this.bar = ...

    // Lots of code
}();

var MAIN2  = function() {
    // Lots of code

    return {
        bar: ...
    }
}();

推荐答案

引用 Douglas Crockford 来自The Good Parts book(第 47 页),回答这个问题的标题:

Quoting Douglas Crockford from the Good Parts book (page 47), to answer the title of this question:

如果 new 操作符是一个方法而不是一个操作符,它可以这样实现:

If the new operator were a method instead of an operator, it could be implemented like this:

Function.method('new', function () {

   // Create a new object that inherits from the 
   // constructor's prototype.

   var that = Object.create(this.prototype);

   // Invoke the constructor, binding -this- to
   // the new object.

   var other = this.apply(that, arguments);

   // If its return value isn't an object,
   // substitute the new object.

   return (typeof other === 'object' && other) || that;
});

Function.method 方法实现如下.这将向类添加一个实例方法(Source):

The Function.method method is implemented as follows. This adds an instance method to a class (Source):

Function.prototype.method = function (name, func) {
   this.prototype[name] = func;
   return this;
};

进一步阅读:

这篇关于new 关键字在底层做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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