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

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

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

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

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

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.

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

4 个解决方案

#1


49

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();

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

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

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

But requires less typing.

但需要更少的打字。

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/

http://jsfiddle.net/jUfdr/

更多相关文章

  1. 豆瓣Javascript代码风格规范
  2. Javascript偏函数与柯里化
  3. 当函数在单独的PHP文件中定义时,调用JavaScript函数onclick按钮事
  4. Python 内置函数及excel操作
  5. Python3 函数式编程(高阶函数)
  6. python中range()函数的用法--转载
  7. Python3入门(六)——函数式编程
  8. 计算机视觉相关代码片段(Python)
  9. 120行python代码解锁10000分微信跳一跳

随机推荐

  1. Android用户体验团队:Android(安卓)UI设计
  2. Unity5 和 Android 通讯(2)
  3. android 状态栏 时间 错误 adb连接
  4. 如何使用APK扩展文件
  5. android 自定义attr 详解
  6. Android的xml文件中引用类型
  7. Android内存管理、监测剖析
  8. android平台解析epub--epublib
  9. Professional Android 2 Development - 2
  10. Android2.1系统在TOP6410上完美运行