Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript passing this to functions

I'm not used to working with this and trying to make some simple functions pass it back and forth. I'm not quite sure what javascript is expecting, but I don't think I'm doing it right.

$(".search-result").each(function() {
    var x  = $(this).find('.past-positions ol').children()
    console.log(x)
    //this prints as expected
    pastJobs(this)
    // this does not
})

function pastJobs() {
    var x  = $(this).find('.past-positions ol').children()
    console.log(x)
    // this prints as undefined
}

I assume its possible to pass this to functions, but I don't think I'm doing it in the right way.

What am I doing wrong?

like image 543
Morgan Allen Avatar asked Mar 04 '23 07:03

Morgan Allen


2 Answers

Try pastJobs.call(this) instead.

like image 144
Sombriks Avatar answered Mar 15 '23 04:03

Sombriks


Actually, here pastJobs(this) you're passing the lexical context this as param rather than binding that context to the function.

You can use the function bind to achieve what you want:

pastJobs.bind(this)()
like image 42
Ele Avatar answered Mar 15 '23 03:03

Ele