admin管理员组

文章数量:1301495

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?

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?

Share edited Mar 24, 2019 at 17:11 Rizwan Khan 2093 silver badges20 bronze badges asked Mar 24, 2019 at 15:18 dropWizarddropWizard 3,54812 gold badges69 silver badges92 bronze badges 2
  • stackoverflow./questions/5611233/… – Paul McLoughlin Commented Mar 24, 2019 at 15:20
  • this and $(this) are two very different things, as the latter is a specific jQuery object while the first change on the how the object is called – Davide Vitali Commented Mar 24, 2019 at 15:31
Add a ment  | 

3 Answers 3

Reset to default 6

Try pastJobs.call(this) instead.

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)()

pastJobs(this) you are passing this as an argument and you're function doesn't accept arguments function pastJobs(). so doing $(this) in pastJobs is really out of context.

you could call the function .call(this)/.apply(this), or bind() and then call it. (bind only binds this object but unlike apply or call doens't invoke the function.

keep in mind that call and apply takes arguments after this object in a different manner. The call() method takes arguments separately. The apply() method takes arguments as an array.

you need something like

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

本文标签: variablesJavascript passing this to functionsStack Overflow