return this"在javascript函数中执行

What does "return this" do within a javascript function?

本文关键字:javascript 函数 执行 this quot return      更新时间:2023-09-26

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

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

"return this"在函数内部做什么?

我知道上面的代码是做什么的,以及"this"关键字的用途。我只是不知道"return this"在函数里面是做什么的

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

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/

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

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

真实示例:jQuery

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

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"); });

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