Reputation: 201
I can always make this work (simple printing of the clicked object):
$("someobject").click(function() {console.log(this)});
and I can always make this work (inserting a pre-made function to execute on click):
$("someobject").click( function() {preMadeFunction(x,y,z)});
but how can I pass this
as an additional argument into a pre-made function I'm inserting? I.e., the object that I've clicked on plays a part in the pre-made inner function I'm inserting, something that would have the effect of this:
$("someobject").click( function() {preMadeFunction(this,x,y,z)});
Upvotes: 0
Views: 47
Reputation: 50749
You can bind the this
when you call your function using .call()
, where the first argument is the this
binding you want to set for your function, and the additional arguments are the function's arguments you want to pass:
function preMadeFunction(x, y, z) {
console.log(this);
console.log(x, y, z);
}
$(".someobject").click(function() {
preMadeFunction.call(this, 1,2,3);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="someobject">A</div>
<div class="someobject">B</div>
<div class="someobject">C</div>
Another option could be to make preMadeFunction
a curried function which closes over your input arguments and returns a function that then gets its this
bounded by jQuery:
function preMadeFunction(x, y, z) {
return function() {
console.log(this);
console.log(x, y, z);
}
}
$(".someobject").click(preMadeFunction(1, 2, 3));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="someobject">A</div>
<div class="someobject">B</div>
<div class="someobject">C</div>
Upvotes: 2