我无法理解jQuery链是如何工作的 [英] I am not able to understand how jQuery chaining works
问题描述
我无法理解jQuery链如何工作。
I am not able to understand how jQuery chaining works.
jQuery("div").attr("id", "_id")
.hide()
.show();
我做了类似链接的事情,但我不确定它是否与jQuery使用的逻辑相同。
I did something like chaining, but I'm not sure if it's the same logic that jQuery uses.
var fun = (function (parma) {
return function () {
return {
start: function () {
console.log("start");
return this;
},
mid: function () {
console.log("mid");
return this;
},
last: function () {
console.log("last");
return this;
}
}
}
})();
// Working
fun().start()
.mid()
.last();
推荐答案
如果函数的返回值是一个对象,有一个方法,你可以立即调用该方法。很简单。
If the return value of a function is an object that has a method, you can call that method immediately. Simple as that.
由于你要返回这个
,你将返回与前一个方法相同的对象被叫了。这意味着你要使用所有相同的方法返回一个对象。
Since you're returning this
, you're returning the same object that the previous method was called on. That means you're returning an object with all the same methods.
这样想:
var f = {
foo: function() {
console.log("foo");
return b;
}
};
var b = {
bar: function() {
console.log("bar");
return f;
}
};
这里我们有两个对象。
Here we have two objects.
-
f
对象有一个名为foo的方法
返回b
对象。 -
b
object有一个名为bar
的方法,它返回f
对象。
- The
f
object has a method calledfoo
that returns theb
object. - The
b
object has a method calledbar
that returns thef
object.
因此,在致电 foo
后,我们可以拨打吧
反之亦然。
Because of this, after calling foo
, we can call bar
, and vice versa.
f.foo().bar().foo().bar(); // etc
但是因为 f
没有' t bar
和 b
没有 foo
,我们永远不能两次调用相同的方法。
But because f
doesn't have bar
and b
doesn't have foo
, we can never call the same method twice.
但是如果我们只有一个对象,它有两种方法,两种方法总是返回相同的原始对象?
But what if we only had one object, that had both methods, and both methods always returned the same original object?
var fb = {
foo: function() {
console.log("foo");
return fb;
},
bar: function() {
console.log("bar");
return fb;
}
};
现在我们总是返回一个同时包含 foo的对象
和 bar
方法,因此我们可以调用任一方法。
Now we're always returning an object that has both the foo
and bar
methods, so we can call either method.
fb.foo().bar().bar().bar().foo().foo().bar();
所以现在唯一真正的区别是我们正在返回 fb
而不是这个
,但它没关系,因为它们是同一个对象。上面的代码可以返回这个;
并且行为相同。
So now the only real difference is that we are returning fb
instead of this
, but it doesn't matter since they're the same object. The code above could do return this;
and it would behave the same.
如果你想要创建对象的多个实例,但 这是面向对象技术的问题,而不是方法链 。
It would matter if you wanted to create several instances of the object, but that's a question of object orientation techniques, not method chaining.
这篇关于我无法理解jQuery链是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!