简体   繁体   中英

Call child's method from parent in jQuery extended object

I've got a child Javascript object

var child = {
    foo: function() {
        console.log('bar');
    }
};

and a parent object

var parent = {
    baz: function() {
        this.foo();
    }
};

merged with jQuery

$.extend(child, parent);

I guess why this works

child.baz();
// prints 'bar'

and this does not

$('#btn').click(child.baz);
// Uncaught TypeError: this.foo is not a function

Thank you

this is DOM element within event handler. You can use $.proxy() to set this to an object within function call

 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> 

You need to modify the code like this:

$('#btn').click(child.baz.bind(child));

The reason your code didn't work was that when click handler is called, this is set to button whereas you want this to be set to child . In javascript this is bound dynamically and is determined by who calls the function. So in first case child.baz(); , implicit binding rule applies and this is set to child . Using bind will hard bind this to child in the button click callback case.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM