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
3 Answers
Reset to default 6Try 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
版权声明:本文标题:variables - Javascript passing this to functions - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741675380a2391851.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论