javascript - 好的部分,增强类型

标签 javascript prototype this

我有一个问题让人想起 JavaScript - The Good Parts: Function prototypes vs Object prototypes .

特别是在“JavaScript: The Good Parts”的第 33 页,我们有以下内容:

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

String.method('trim', function () { 
  return this.replace(/^\s+|\s+$/g, ''); 
});


console.log( "foo  ".trim() ); // Not in "JavaScript: The Good Parts" but added for discussion.

return this;Function.prototype.method 中的目的是什么 - 是允许“点链”还是“以级联方式编程”在第 49 页的顶部注意到了吗?

此外,系统如何知道 this 指的是 String.method 中的字符串文字 "foo "

最佳答案

这是为了启用在一个对象上创建多个方法的 dotchaining 或流畅方法。

例如……

String
  .method('one', function(){})
  .method('two', function(){})....

关于javascript - 好的部分,增强类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26515088/

相关文章:

Javascript 在分配给其他变量时丢失了上下文

javascript - 有没有有效的方法将我的 <span> 元素包含在以下 JavaScript 中?

javascript - 向 D3 图形 y 轴标签添加换行符

javascript - 解析XML以获取节点值

javascript - 如何使用 JavaScript/Prototype 1.7 递归搜索对象树并根据键/值返回匹配对象

javascript - 对 JavaScript 原型(prototype)继承与构造函数感到困惑

javascript - 在 Function.prototype 中得到 "TypeError: Cannot convert undefined or null to object"

javascript - 将 js 对象更改为带有嵌套可观察数组的 knockout js View 模型

Javascript对象原型(prototype)错误

java - 为什么具有不同参数的多个 `this()` 在父构造函数中不起作用?