简体   繁体   中英

Using object variable within function. JavaScript

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?

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

Welcome to the "this" key word!

Just reference it by this.value

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM