簡體   English   中英

在jQuery擴展對象中從父級調用子級方法

[英]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將很難結合thischild的按鈕,點擊回調的情況下。

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM