[英]Call child's method from parent in jQuery extended object
我有一個子Javascript對象
var child = {
foo: function() {
console.log('bar');
}
};
和一個父對象
var parent = {
baz: function() {
this.foo();
}
};
與jQuery合並
$.extend(child, parent);
我想這為什么有效
child.baz();
// prints 'bar'
而且這不
$('#btn').click(child.baz);
// Uncaught TypeError: this.foo is not a function
謝謝
this
是事件處理程序中的DOM
元素。 您可以使用$.proxy()
來設置this
函數調用中的一個對象
var child = { foo: function() { console.log('bar'); } }; var parent = { baz: function() { this.foo(); } }; $.extend(child, parent); $("#btn").click($.proxy(child.baz, child));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <div id="btn">click</div>
您需要像這樣修改代碼:
$('#btn').click(child.baz.bind(child));
你的代碼沒有工作的原因是,當點擊處理程序被調用, this
而你想設置為按鈕this
設置為child
。 在javascript中, this
是動態綁定的,由誰調用該函數確定。 所以在第一種情況下child.baz();
隱式綁定規則適用, this
被設置為child
。 使用bind
將很難結合this
對child
的按鈕,點擊回調的情況下。
var child = { foo: function() { console.log('bar'); } }; var parent = { baz: function() { this.foo(); } }; $.extend(child, parent); child.baz(); $('#btn').click(child.baz.bind(child));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="btn">Click</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.