什么是“返回这个”在javascript函数内做什么? [英] What does "return this" do within a javascript function?

查看:114
本文介绍了什么是“返回这个”在javascript函数内做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i wonder, what does "return this" do within a javascript function, what's its purpose? supposing we have the following code:

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

函数内部返回此是什么?

What does "return this" do inside of a function?

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

I know what code above does, and what is the use of "this" keyword. I just don't know what "return this" does inside of a function.

推荐答案

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

It refers to the object instance on which the method is currently being called. It's used for chaining. For example, you could do something like this:

myObject.foo().bar();

由于 foo 返回(对 myObject 的引用), bar 也将在对象上调用。这与做

Since foo returns this (a reference to myObject), bar will be called on the object too. This is the same thing as doing

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

但需要更少的输入。

这里是一个更完整的例子:

Here is a more complete example:

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/

这篇关于什么是“返回这个”在javascript函数内做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆