Kingshukrox
Kingshukrox

Reputation: 59

how to access the value in a function which is defined inside a key of an object in javascript

i have passed the value 'hp' to the key function get() and can access it in the next line when it log it to console and then i proceed to pass the same variable to another function set() which is defined inside of the key function get() but the value is undefined when i try to access it in log statement of the inner function. note- If i dont pass the variable company inside set() i can access it. I have just started learning JS so any links would be appreciated.

var laptop = {
  company: "none",

  get: function(company) {
    console.log("outer", company);

    var set = function(company) {
      console.log("inner", company);
    };
    set();
  }
};
laptop.get("hp");

Upvotes: 0

Views: 103

Answers (1)

goto
goto

Reputation: 4425

I think what you're looking for is something like the following:

var laptop = {
  company: "none",

  get: function(company) {
    // use `this` to access the object's properties
    console.log("outer", this.company);

    var set = function(arg) {
      console.log("inner", arg);
      
      // alternatively, just use `company`
      // because of `closures`, which give you 
      // access to an outer function's scrope 
      // from an inner function
      console.log("inner #2", company);
    };
    set(company);
  }
};

laptop.get("hp");

However, I'd strongly advise against using the same name for your variables/arguments/parameters inside the same scope, the way you have it in your example, to avoid confusion.

Learn more about closures in JavaScript:

Upvotes: 1

Related Questions