【问题标题】:What does return this in Function.prototype.method do? [duplicate]Function.prototype.method 中的 return this 有什么作用? [复制]
【发布时间】:2013-11-12 19:46:17
【问题描述】:

我刚开始阅读 JavaScript: The Good Parts,我已经对 Function.prototype.method 中的“return this”做了什么感到困惑?我了解“这个”和“返回”是如何工作的。 'this' 本质上是当前对象的指针,'return' 简单地退出函数,同时输出一个值(如果您描述了任何值);在我们的例子中,'this'。

这是我引用的代码。

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

/* SIMPLE CONSTRUCTOR */
function Person(name, age) {
    this.name = name;
    this.age = age;
}

/* ADD METHODS */
Person.method('getName', function() { return this.name; });
Person.method('getAge', function() { return this.age; });

var rclark = new Person('Ryan Clark', 22);

console.log(rclark.getName()); // string(Ryan Clark)
console.log(rclark.getAge()); // number(22)

我尝试省略“return this”以查看代码是否会中断,但不会? 'return this' 究竟是做什么的?我将继续阅读这本书,但我想确保我理解了所有内容。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript oop prototype


    【解决方案1】:

    它允许链接,因此您可以执行以下操作:

    /* ADD METHODS */
    Person.method('getName', function() { return this.name; })
          .method('getAge', function() { return this.age; });
    

    【讨论】:

    • 简单的A++解释!就像 jQuery 在某些方面的工作方式一样。
    【解决方案2】:

    return this 返回调用method() 的对象,并在通过添加传递的方法对其进行修改后。

    省略它不会破坏您的代码,但它是一种更好的样式,允许链式方法调用,因此您可以:

    Person.method('getName', function() { return this.name; }).method('getAge', function() { return this.age; });
    

    【讨论】:

    • 我从来没有真正想过这个。是不是本书后面会解释的东西?但是,如果省略了“return this”并且您尝试链接,它会破坏您的代码,因为您将试图链接到任何东西。
    • @W3Geek 不知道书后面有没有解释,但我是从经验中学到的。
    猜你喜欢
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 2013-08-09
    • 2016-03-27
    • 2011-08-22
    • 1970-01-01
    • 2017-01-17
    相关资源
    最近更新 更多