2015-08-15 49 views
1

爲什麼此代碼的屬性在點擊事件後未顯示?爲什麼這個jQuery OOP屬性變得不確定?

屬性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>

+0

這屬於特定的上下文,你使用它在裏面的功能,所以這是覆蓋那裏 – dom

回答

2

因爲一旦你進入ShoutCount方法,this的作用域是方法,而不是外部方法。您需要使用bind來附加您想要的範圍,例如

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

我明白了,謝謝! – Ryan

相關問題