我想知道,“return this”在 javascript 函数中做什么,它的目的是什么?
假设我们有以下代码:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
“return this”在函数内部做什么?
我知道上面的代码是做什么的,以及“this”关键字的用途是什么。我只是不知道“return this”在函数内部的作用是什么。
它指的是当前正在调用该方法的对象实例。它用于链接。例如,您可以执行以下操作:
myObject.foo().bar();
Since 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/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)