Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference another field inside a javascript object

Tags:

javascript

I have an object in javascript:

admins: {
    articles: {
        path: '/admins/articles',
        template: '/views/admins/articles.html',
        link: function() {
            return path;  // !!! how to reference the 'path'?
        }
    }
}

I have a lot of objects like this, and each of them has a path field and a link function. I want to use the field path in link, but I can't just use path.

What should I do?

like image 772
Freewind Avatar asked Jul 20 '12 02:07

Freewind


3 Answers

You can use this to reference the object. Standard object.method() "dot" syntax will set this to object within method:

var someObj = {
    admins: {
        articles: {
            path: '/admins/articles',
            template: '/views/admins/articles.html',
            link: function() {
                return this.path; // !!! how to reference the 'path'?
            }
        }
    }
};

var returnedPath = someObj.admins.articles.link();

Demo: http://jsfiddle.net/2Pt7n/

(There are other ways to call a function such that this will not be set to the appropriate object, but I hope they don't apply here - you don't really say how you're using the objects or calling the function, but if not in the way I showed then please update your question and I'll update my answer accordingly.)

like image 105
nnnnnn Avatar answered Nov 13 '22 14:11

nnnnnn


I'll just point out that you don't want to use ES6 fat arrow here, because there will be no this pointer in that case:

var someObj = {
    admins: {
        articles: {
            path: '/admins/articles',
            template: '/views/admins/articles.html',
            link: () => {
                return this.path; // 'this' is undefined
            }
        }
    }
};

someObj.admins.articles.link() === undefined

like image 44
Jeff Lowery Avatar answered Nov 13 '22 13:11

Jeff Lowery


What you are showing is not JSON. It is a Javascript object, which is different than JSON. JSON is a strictly defined data serialization format that is a subset of Javascript object literals.

Javascript provides no syntax for referencing peer properties in an object literal, as you want to do. Naming them is one idea, but it won't help, because the name won't exist while the literal is being defined, so the name is not available for you to use in the literal itself.

Also, note that the syntax you define makes the object lop-sided: you can access path as obj.admins.articles.path, but link is a function you would have to invoke: obj.admins.articles.link().

like image 2
Ned Batchelder Avatar answered Nov 13 '22 13:11

Ned Batchelder