好的零件,增强类型

时间:2014-10-22 19:01:12

标签: 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.

Function.prototype.method 返回此的目的是什么 - 是否允许"点链接"或者"以级联风格编程"如第49页顶部所述?

此外,系统如何知道引用 String.method " foo" >

1 个答案:

答案 0 :(得分:1)

启用点链或流畅的方法在对象上创建多个方法。

例如......

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