新关键字在幕后做了什么?

Ray*_*nos 15 javascript oop prototype object new-operator

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

例如,如果我们使用new关键字比较来使对象上的函数集属性和方法只是使函数返回一个新对象,那么新对象有什么额外的作用吗?

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

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;
  }
}();
Run Code Online (Sandbox Code Playgroud)

firebug探测器告诉我使用new关键字稍微快一点(2ms而不是3ms),对大型对象来说新的仍然明显更快?

[编辑]

另一个问题是真正大的对象构造函数在函数的底部有一个返回(它将具有大量的本地函数)或者有一些this.bar = ...在函数的顶部更具可读性?什么被认为是一个好的约定?

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

    // Lots of code
}();

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

    return {
        bar: ...
    }
}();
Run Code Online (Sandbox Code Playgroud)

Dan*_*llo 17

引用道格拉斯克罗克福德好的部分书(第47页),回答这个问题的标题:

如果new运算符是方法而不是运算符,则可以像这样实现:

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;
});
Run Code Online (Sandbox Code Playgroud)

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

Function.prototype.method = function (name, func) {
   this.prototype[name] = func;
   return this;
};
Run Code Online (Sandbox Code Playgroud)

进一步阅读:

  • 现在我只需要弄清楚this.prototype,this.apply和Function.method在内部做什么:).有时候我觉得我应该假设和破解更多,并尝试更少了解内部. (2认同)

Tim*_*own 6

阅读规范.第11.2.2节和第13.2.2节是相关的,并且不太难理解(注意后两个链接是非官方的HTML-ified版本的规范).

总之,如果你有一个函数f返回一个对象,唯一可见差异与调用它new将使就是this值会有所不同,而且与调用它new 可能会比较慢,因为它涉及到创建对象的额外的步骤和为它分配一些属性.