I have a custom class that looks like:
开发者_JAVA技巧function myClass(){
var thing;
var thingtype;
}
I am using a third-party library to create and manage 'A'-type 'things', and a second third-party library to create and manage 'B'-type things.
When my A or B type thing loads, I would like to execute a callback.
Suppose the first third-party library broadcasts an onLoad
event when an A-type thing loads, and the second library broadcasts an onReady
event when a B-type thing loads.
I could say:
if (thingtype=='A'){
thing.onLoad(function(){alert ("my callback");})
}
if (thingtype=='B'){
thing.onReady(function(){alert ("my callback");});
}
My question: Is it possible to instead use a variable for the event-name, something like:
if (thingtype=='A'){
myLoadEvent = 'onLoad';
}
if (thingtype=='B'){
myLoadEvent = 'onReady';
}
thing.myLoadEvent(function(){alert ("my callback");});
onLoad
and onReady
are normal properties of the thing
object. To access any property using its string name, use obj[x]
to look up that value:
thing[myLoadEvent](function(){alert ("my callback");});
Here's a simpler example to illustrate this concept:
var foo = {
bar: function() { return 'baz'; }
};
console.log(foo.bar()); // => 'baz'
console.log(foo['bar']()); // => 'baz'
console.log(foo.bar() === foo['bar']()); // => true
精彩评论