jquery 链接是如何工作的?

2022-01-16 00:00:00 frameworks jquery javascript

我不是在问什么是适当的链接语法,我知道它可能是这样的:

I am not asking what is the appropriate syntax for chaining, I know it could be something like:

$('myDiv').removeClass('off').addClass('on');

但是我真的很想了解它的内部工作原理,据我所知,链接是相对于其他著名框架的优势之一,但是对于像我这样的新手程序员来说,这对于我们来说非常抽象,我敢肯定有没有人可以为我提供解释,让我了解链接的工作原理.

However I'm really curious to understand the inner working of it, as far as I know chaining is one of the advantages against other famous frameworks but this us to much abstraction for a novice programer like me, I'm sure there is someone out there that can provide me with a explanation that allows me to understand how chaining works.

谢谢!

推荐答案

如果你有一个带有某些方法的对象,如果每个方法返回一个带有方法的对象,你可以简单地从返回的对象中调用一个方法.

If you have an object with certain methods, if each method returns an object with methods, you can simply call a method from the object returned.

var obj = {   // every method returns obj---------v
    first: function() { alert('first');   return obj; },
    second: function() { alert('second'); return obj; },
    third: function() { alert('third');   return obj; }
}

obj.first().second().third();

演示: http://jsfiddle.net/5kkCh/

相关文章