【问题标题】:JavaScript: Augmenting types - Purpose of "return this" [duplicate]JavaScript:增强类型 - “返回这个”的目的 [重复]
【发布时间】:2015-04-16 08:14:04
【问题描述】:

我目前正在阅读 JavaScript - The Good Parts。所以我处理了类型的增加。 我理解动机和实施。但是如果我看代码...

Function.prototype.method = function(ident, funct) {
    this.prototype[ident] = funct;
    return this; // No idea. For what?
};

...那我不明白退货的目的。 我已经把回报放在了 cmets 中。那没有效果。无论如何它都起作用了。

我的完整代码:

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

Date.method('sayHello', function() {
    alert(new Date().toString());
});

var myDate = new Date();

myDate.sayHello();

那它是干什么用的?

【问题讨论】:

标签: javascript


【解决方案1】:

通常这样做是为了让您可以链接方法调用,即所谓的“流畅接口”:

obj.method().anotherMethod().yetAnotherMethod()

例如:

'string'.toUpperCase().substr(2).repeat(3)

如果是字符串,如果this,则返回另一个新字符串,但您知道它为什么有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 2021-04-15
    • 2012-06-13
    • 2010-11-25
    • 2015-06-06
    相关资源
    最近更新 更多