JS 模块化模式 - public 函数未执行

JS Modular Pattern - public function not executing

$( document ).ready(function() {
  var feature = (function() {
    var items = $( "#myFeature li" );

    var showItem = function() {
      currentItem = $( this );
      // more code goes here;
    };
 
    var showItemByIndex = function( idx ) {
      $.proxy( showItem, items.get( idx ) );
    };       
 
    items.click( showItem );
 
    return {
      showItemByIndex: showItemByIndex
    };
  })();
 
  feature.showItemByIndex( 0 );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myFeature">
  <ul>
     <li>item 1</li>
     <li>item 2</li>
  </ul>
</div>

以上代码片段来自 jQuery 文档,来自此处 https://learn.jquery.com/code-organization/concepts/

public 函数 feature.showItemByIndex(0) 没有执行,有人可以解释一下吗?

看起来 showItemByIndex 函数在页面加载时由 feature.showItemByIndex( 0 ) 行调用。

问题是 showItemByIndex 实际上并没有做任何有用的事情;它为 showItem 创建一个代理函数(绑定 this 关键字),然后不对其执行任何操作。

如果您修改示例以便调用新创建的代理函数,那么代码将按预期执行。

$( document ).ready(function() {
  var feature = (function() {
    var items = $( "#myFeature li" );

    var showItem = function() {
      currentItem = $( this );
      console.log('Show Item',this) // added some logging
    };
 
    var showItemByIndex = function( idx ) {
      $.proxy( showItem, items.get( idx ) )(); // call this proxy function!
    };       
 
    items.click( showItem );
 
    return {
      showItemByIndex: showItemByIndex
    };
  })();
 
  feature.showItemByIndex( 0 );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myFeature">
  <ul>
     <li>item 1</li>
     <li>item 2</li>
  </ul>
</div>