I’m having an issue with my javascript code.
I am calling a function and passing in args
Inside the function, if I console.log
it like this: console.log(args);
I can see the args object in the browser console and I can click down to this:
args > model > id
And the id is 9483
But if I try to use the this
keyword like this:
console.log(this.model.id)
I get this error:
this.model.id is undefined
I thought this
would bind to my args that are passed in.
What could i be doing wrong?
Here is the function:
function lookUp(args) {
console.log("lookUp :: args ==> ", args);
console.log("lookUp :: this.model.id ==> ", this.model.id);
Thanks!
3
Answers
this refers to the object / scope that is executing your function. In your case that’s global
this
doesn’t bind to the args that are being passed in.this
is a context depending on how the function is called.If you want to set it explicitly you can try:
Hope that helps.
what Mozilla says about this in a function
I don’t know the entire section of relevant affected code and I know you are talking about a function, but in case of objects, as a general rule when I need to keep track context from a Object I use
then I use
self
where is needed, usually inside a closure.- Which is probably what are you looking for.