加载中...

迭代器模式


迭代器模式

迭代器模式中,迭代器(允许我们遍历集合中所有元素的对象)顺序迭代一个集合对象中的元素而无需暴漏其底层形式。

迭代器封装了这种特别的迭代操作的内部结构,就jQuery的jQuery.fn.each()迭代器来说,我们实际上可以使用jQuery.each()底层的代码来迭代一个集合,而无需知道或者理解后台提供这种功能的代码是如何实现的。

这种模式可以被理解为门面模式的一种特例,在这里我们只处理与迭代有关的问题。

  1. $.each( ["john","dave","rick","julian"] , function( index, value ) {
  2. console.log( index + ": "" + value);
  3. });
  4. $( "li" ).each( function ( index ) {
  5. console.log( index + ": " + $( this ).text());
  6. });

这里我们可以看到jQuery.fn.each()的代码:

  1. // Execute a callback for every element in the matched set.
  2. each: function( callback, args ) {
  3. return jQuery.each( this, callback, args );
  4. }

在jQuery.each()方法后面的代码提供了两种迭代对象的方法:

  1. each: function( object, callback, args ) {
  2. var name, i = 0,
  3. length = object.length,
  4. isObj = length === undefined || jQuery.isFunction( object );
  5. if ( args ) {
  6. if ( isObj ) {
  7. for ( name in object ) {
  8. if ( callback.apply( object[ name ], args ) === false ) {
  9. break;
  10. }
  11. }
  12. } else {
  13. for ( ; i < length; ) {
  14. if ( callback.apply( object[ i++ ], args ) === false ) {
  15. break;
  16. }
  17. }
  18. }
  19. // A special, fast, case for the most common use of each
  20. } else {
  21. if ( isObj ) {
  22. for ( name in object ) {
  23. if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
  24. break;
  25. }
  26. }
  27. } else {
  28. for ( ; i < length; ) {
  29. if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
  30. break;
  31. }
  32. }
  33. }
  34. }
  35. return object;
  36. };

还没有评论.