javascript - Crockford "new"方法

标签 javascript apply invocation

希望有人能帮我分解 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;
});

我不明白的部分是当他使用应用调用模式创建对象时:

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

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

如果函数将是:

var f = function (name) {
   this.name = "name";
};

调用方式:

var myF = f.new("my name");

创建对象?

最佳答案

首先注意Function.method isn't a built-in JS method .有点东西Crockford made up :

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

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

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

然后当你使用它的时候

f.new("my name");

它这样做:

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

关于javascript - Crockford "new"方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32513148/

相关文章:

python - 基于索引、列名和原始值映射 Pandas 数据框?

r - 将带时间戳的数据与另一个数据集中最接近的时间进行匹配。正确矢量化?更快的方法?

function - 使用列表中的名称调用计划函数

perl - 为什么语法 `&name arg1 arg2 ...` 不能用于调用 Perl 子程序?

javascript - 在javascript中组合N个数组值

javascript - 如何在 jQuery 中构建滑动菜单

r - 如何自定义外部函数和矢量化函数?

Javascript网络音频均方根不读取流

javascript - 如何从 discord.js 中的 JSON 文件中选择随机对象

抽象数据类型中方法调用的 Java 顺序?