Reading Object Literal in JS with function result
I have an object literal:
var content = {
classname1:"content",
classname2:"content"
}
Accessing in this way content.classname1
is easy. But I do not want to state classname1
rather than using a function to get that classname and pass it to my object:
function getMyClass {
// some code
return myclass;
}
content.myclass
where myclass
is the result of a function. But that does not work. I do not know how to concatenate the content.
with the result of the function.
The background is: I want tooltips to be displayed for 开发者_JAVA百科nearly everthing on my site. So one function schould find out the class of the element and then display it the content associated to it from the object literal. So managing classname and content would be pretty easy.
Thanks.
obj.property
is syntactic sugar for obj['property']
You can access the members of an object using []
notation instead of dotted notation. If you use brackets, then you can place anything that evaluates to a string between the brackets. This allows you to dynamically specify properties, or to use property names that aren't valid JavaScript identifiers... for example obj['2nd property']
So, try:
content[getMyClass()]
function getMyClass {
// some code
return "myclass";
}
content["myclass"];
This might be what your looking for. Your question is a bit vague.
Alternatively you could try:
for (var key in content) {
if (content.hasOwnProperty("key")) {
addContent(key, content[key]);
}
}
function addContent(className, content) {
// do stuff
}
If you want to use a function (perhaps there's more logic than simply selecting the value of a property), here's one way:
var content = {
classname1:"contentbbbb",
classname2:"contentaaaa",
getClassName : function(which){
// do stuff, check things
return this[which];
}
}
Then you'd have:
content.getClassName('classname1'); // returns 'contentbbbb'
精彩评论