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

时间:2010-09-06 10:57:31

标签: 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;
  }
}();

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

[编辑]

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

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

    // Lots of code
}();

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

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

2 个答案:

答案 0 :(得分:17)

Douglas Crockford(第47页)引用the Good Parts book,回答此问题的标题:

  

如果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;
});

Function.method方法实现如下。这会向类(Source)添加实例方法:

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

进一步阅读:

答案 1 :(得分:6)

阅读the spec。章节11.2.213.2.2是相关的,并且不太难理解(请注意后两个链接是非官方的HTML-ified版本的规范)。

总之,如果你有一个返回一个对象的函数f,那么用new调用它的唯一可观察差异就是this值会有所不同,并且使用new 调用它可能会变慢,因为它涉及创建对象和为其分配一些属性的其他步骤。