skip to Main Content

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


  1. this refers to the object / scope that is executing your function. In your case that’s global

    Login or Signup to reply.
  2. 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:

    lookUp.call(useAsThis, …args);
    

    Hope that helps.

    Login or Signup to reply.
  3. what Mozilla says about this in a function

    Inside a function, the value of this depends on how the function is
    called. Think about this as a hidden parameter of a function — just
    like the parameters declared in the function definition, this is a
    binding that the language creates for you when the function body is
    evaluated.

    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

    let self = this;
    

    then I use self where is needed, usually inside a closure.- Which is probably what are you looking for.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search