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?
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.)
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
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With