什么“返回此”在javascript函数中做什么?
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/
更多相关文章
- 豆瓣Javascript代码风格规范
- Javascript偏函数与柯里化
- 当函数在单独的PHP文件中定义时,调用JavaScript函数onclick按钮事
- Python 内置函数及excel操作
- Python3 函数式编程(高阶函数)
- python中range()函数的用法--转载
- Python3入门(六)——函数式编程
- 计算机视觉相关代码片段(Python)
- 120行python代码解锁10000分微信跳一跳