简体   繁体   English

在函数内使用对象变量。 JavaScript的

[英]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. 我最近开始学习JavaScript,想知道是否有可能直接在同一对象内的函数中使用对象变量。 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. 大多数情况下 ,您可以仅使用this关键字来获取在其上调用函数的对象作为方法。 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 只需引用this.value

You can use the this keyword . 您可以使用this关键字。 You can better understand this keyword using this article 您可以通过本文更好地了解this关键字

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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