克罗克福德的"新"方法

Dan*_*hua 3 javascript invocation apply

希望有人可以帮我打破Crockford JS Good Parts的一小段代码:

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)

我不理解的部分是他使用apply调用模式创建一个对象:

var other = this.apply(that, arguments);
Run Code Online (Sandbox Code Playgroud)

如何执行函数将创建新对象?

如果该功能将是:

var f = function (name) {
   this.name = "name";
};
Run Code Online (Sandbox Code Playgroud)

怎么称呼:

var myF = f.new("my name");
Run Code Online (Sandbox Code Playgroud)

创造对象?

Ori*_*iol 5

首先,注意Function.method不是内置的JS方法.这是Crockford编造的东西:

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

因此,该Function.method方法调用基本上是这样的:

Function.prototype.new = function() {
  var that = Object.create(this.prototype);
  var other = this.apply(that, arguments);
  return (typeof other === 'object' && other) || that;
});
Run Code Online (Sandbox Code Playgroud)

然后当你使用它时

f.new("my name");
Run Code Online (Sandbox Code Playgroud)

它这样做:

  1. 首先,它创建一个继承自f.prototype(实例)的对象.
  2. 然后,它调用f传递该实例作为this值.
    • 在这种情况下,这会将name属性设置为实例.
    • 此步骤不会创建任何新实例,该实例是在步骤1中创建的.
  3. 如果调用f返回一些对象,则返回该对象.
    否则,返回在步骤1中创建的实例.