什么"返回此"在javascript函数中做什么?

use*_*756 41 javascript

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

Function.prototype.method = function (name, func) {
  this.prototype[name] = func;
  return this;
};
Run Code Online (Sandbox Code Playgroud)

什么"返回这个"在函数内部做什么?

我知道上面的代码是什么,以及"this"关键字的用途是什么.我只是不知道函数内部有什么"返回这个".

Ale*_*pin 53

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

myObject.foo().bar();
Run Code Online (Sandbox Code Playgroud)

由于foo返回this(到参考myObject),bar将在对象上被调用过.这与做同样的事情

myObject.foo();
myObject.bar();
Run Code Online (Sandbox Code Playgroud)

但需要更少的打字.

这是一个更完整的例子:

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();
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/jUfdr/


mar*_*cio 13

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

MyObject.method1().method2().method3();
Run Code Online (Sandbox Code Playgroud)

真实世界的例子:jQuery

$(this).addClass('myClass').hide();
Run Code Online (Sandbox Code Playgroud)

  • +1这实际上就是jQuery的名气. (7认同)

Ada*_*kis 11

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


this 指当前上下文,并根据您调用函数的方式更改含义.

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

使用方法调用,this指的是调用方法的对象.

使用apply invocation,this指的是调用apply时设置的内容.

使用构造函数调用时,this引用在后台为您创建的对象,在构造函数退出时返回该对象(假设您没有错误地从构造函数中返回自己的对象).

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

所以你可以这样做:

Car.method("vroom", function(){ alert("vroom"); })
   .method("errrk", function() { alert("errrk"); });
Run Code Online (Sandbox Code Playgroud)

等等.