我有一个问题让人想起 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/