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

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

问题描述

我很好奇 new 关键字除了更改范围引用的内容之外还有什么用呢?

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探测器告诉我使用new关键字稍快一些(2ms而不是3ms),大对象是新的仍然明显更快?

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 来自好零件书(第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;
};

进一步阅读:

  • Mozilla Dev Center: Object.create()
  • Mozilla Dev Center: Function.apply()
  • Douglas Crockford: Classical Inheritance in JavaScript

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

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