0

I have recently started to learn JavaScript and would like to know if it is possible to use a object variable in a function directly within the same object. Here is my code so far.

    var user = {
    name: 'Example',
    age: 687,
    address: {
    firstLine: '20',
    secondLine: 'St Fake',
    thirdLine: 'Fakeland'   
    },
    logName: function(inputName, inputAge){
    console.log(user.name);
    console.log(user.age);
    console.log(inputAge);
    console.log(inputName);
    }
    };

    user.logName('Richard', 20);

How is it possible to link to the name and age variables of user in the function without needing to prefix the object name onto the variable?

hudsond7
  • 666
  • 8
  • 25

3 Answers3

2

In most cases, you can just use the this keyword to get the object on which your function was called as a method upon. In your example:

var user = {
    name: 'Example',
    age: 687,
    address: {
        firstLine: '20',
        secondLine: 'St Fake',
        thirdLine: 'Fakeland'   
    },
    logName: function(inputName, inputAge) {
        console.log(this.name);
//                  ^^^^
        console.log(this.age);
//                  ^^^^
        console.log(inputAge);
        console.log(inputName);
    }
};

user.logName('Richard', 20); // method call on `user`,
                             // so `this` will become the `user` in the function
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Welcome to the "this" key word!

Just reference it by this.value

Sten Muchow
  • 6,623
  • 4
  • 36
  • 46
1

You can use the this keyword . You can better understand this keyword using this article

The code will be like this

var user = {
    name: 'Example',
    age: 687,
    address: {
        firstLine: '20',
        secondLine: 'St Fake',
        thirdLine: 'Fakeland'
    },
    logName: function (inputName, inputAge) {
        console.log(this.name);
        console.log(this.age);
        console.log(inputAge);
        console.log(inputName);
    }
};

user.logName('Richard', 20);
Shiva
  • 6,677
  • 4
  • 36
  • 61