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?

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

1

Welcome to the "this" key word!

Just reference it by this.value

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.