为什么这个 jQuery OOP 属性 变得未定义?

Why does this jQuery OOP property became undefined?

为什么这个代码的属性在点击事件后没有显示?

属性 this.ContainerId 在进入 this.ShoutCount 方法时变为未定义。

谢谢。

var table = function (containerId) {
  this.ContainerId = containerId;
  
  this.ShoutCount = function (totalC) {
        var label = $("#" + this.ContainerId + " .result").text();
        alert(totalC + " " + label);
  }
  this.ClickCount = function (sc) {
    $("#" + this.ContainerId + " .showTotalCount").click(function () {
      sc($(this).text());
    });
  }
  this.ClickCount(this.ShoutCount);
}

var t = new table("user-tab-pagination");
<div id="user-tab-pagination">
  <div class="search-count"><span class="showTotalCount">100</span> <span class="result">Result(s)</span></div>
</div>

因为一旦您进入 ShoutCount 方法,this 的作用域就是该方法,而不是外部方法。您需要使用 bind 附加您想要的范围,例如

this.ShoutCount = function (totalC) {
  var label = $("#" + this.ContainerId + " .result").text();
  alert(totalC + " " + label);
}.bind(this);