【问题标题】:What does "return this" do within a javascript function?“返回这个”在 javascript 函数中做了什么?
【发布时间】:2011-11-28 18:59:11
【问题描述】:

我想知道,“返回这个”在 javascript 函数中做了什么,它的目的是什么? 假设我们有以下代码:

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

“return this”在函数内部做了什么?

我知道上面的代码做了什么,以及“this”关键字的用途。我只是不知道“返回这个”在函数内部做了什么。

【问题讨论】:

  • @user722756:因为method 被添加到Function.prototypethis 将引用调用method 的函数。该函数可能被用作“构造函数”,因为method 正在扩展该函数的prototype 对象。
  • 我知道“this”关键字的用法我只是不知道函数内部“return this”的用法。
  • return this 用于创建fluent interface。请参阅下面@marcioAlmada 和@AdamRackis 发布的答案。
  • 我猜你没有理解我的问题。我知道上面的代码是做什么的,我只是不知道“return this”是做什么的。

标签: javascript


【解决方案1】:

它指的是当前正在调用该方法的对象实例。它用于链接。例如,您可以这样做:

myObject.foo().bar();

由于foo 返回this(对myObject 的引用),因此也会在对象上调用bar。这和做的一样

myObject.foo();
myObject.bar();

但需要更少的打字。

这是一个更完整的例子:

function AnimalSounds() {}

AnimalSounds.prototype.cow = function() {
    alert("moo");
    return this;
}

AnimalSounds.prototype.pig = function() {
    alert("oink");
    return this;
}

AnimalSounds.prototype.dog = function() {
    alert("woof");
    return this;
}

var sounds = new AnimalSounds();

sounds.cow();
sounds.pig();
sounds.dog();

sounds.cow().pig().dog();

http://jsfiddle.net/jUfdr/

【讨论】:

  • 既然扩展prototype 就是它的作用,为什么不使用实际代码来说明呢? AnimalSounds.method( 'cow', func... ).method( 'pig', func... ).method( 'dog', func... );
【解决方案2】:

这意味着该方法将返回它所属的对象。如果您想像这样链接指令,这可能很有用:

MyObject.method1().method2().method3();

现实世界的例子:jQuery

$(this).addClass('myClass').hide();

【讨论】:

    【解决方案3】:

    tl;dr 从方法返回this 是允许将方法“链接”在一起的常用方法。


    this 引用当前上下文,并根据您调用函数的方式改变含义。

    对于函数调用,this 指的是全局对象,即使该函数是从一个方法调用的,并且该函数与调用它的方法属于同一个类。 Douglas Crockford 将此描述为“语言设计中的错误”[Crockford 28]

    通过方法调用,this 指的是在其上的对象 方法正在被调用。

    使用 apply 调用,this 指的是您在调用 apply 时设置的任何值。

    使用构造函数调用,this 指的是对象 在幕后为您创建,当 构造函数退出(前提是你没有错误地从构造函数返回你自己的对象)。

    在上面的示例中,您正在创建一个名为method 的新方法,该方法允许您动态添加函数并返回this,从而允许链接。

    所以你可以这样做:

    Car.method("vroom", function(){ alert("vroom"); })
       .method("errrk", function() { alert("errrk"); });
    

    等等。

    【讨论】:

      【解决方案4】:

      它返回this,通常表示调用它的html元素,但“this”可以有多种含义 http://www.quirksmode.org/js/this.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-04
        • 2018-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-24
        • 2019-04-30
        • 1970-01-01
        相关资源
        最近更新 更多