![]() |
issues understanding code
Hello,
I have some issues to understand how parts of the following code are working: demo: http://devfiles.myopera.com/articles/649/example2.html source: http://devfiles.myopera.com/articles/649/example2.js this is the part I have issues with: Code:
var func = tool[ev.type];Any help is welcome, thanks in advance! |
Functions in JavaScript *ARE* objects.
So you can get a reference to a function just as you can get a reference to any other kind of object. And, if you indeed you *have* a reference to a function, then you can invoke the function via that reference. Perhaps a simple example will help: Code:
function demo(arg) { alert("demo called with argument " + arg); } |
thanks this indeed got me somewhat closer. I still have issues with the following though:
Quote:
Thanks in advance |
Presumably there is more code than what you posted and the tool[] array is being defined somewhere in the rest of the code.
From just the portion of code you supplied we can say that tool[ev.type] can be either a function or code that returns a function. |
Quote:
|
Code:
but I don't get the whole idea of why tool[ev.type] is an arrayCode:
var myObject = { "name": "Bob" };Code:
myObject.func = function () { alert("Hello!") };Code:
func(ev);These are general details - I didn't examine the page in detail. |
Quote:
It never was and still isn't. It is an object. Let's say that we *KNOW* that ev.type is "mouseup". That means that doing tool[ev.type] is of course equivalent to doing tool["mouseup"] (no mystery there, right?).But...and here may be the surprise to you... tool["mouseup"] is equivalent to tool.mouseup !!!SO... If we have an object such as this: Code:
var tool = {Code:
var func = tool[ev.type];Code:
var func = tool["mouseup"];Code:
var func = tool.mouseup;Code:
var func = function(x) { alert("mouse up called with argument" + x); }Code:
func( ev );Code:
alert("mouse up called with argument" + ev); |
excellent ^^ thanks this indeed helped me alot. I was not aware of the whole objects <=> associative array thingie and will look into it. it makes perfect sense now thanks to your explanation.
just a last small question out of curiousity: is there another way to write tool[ev.type]? I don't think tool.ev.type would work, would it? :) |
Quote:
Code:
tool[ev['type']] |
Quote:
Suppose you had: Code:
var tool = {Code:
tool["mouseup"]It might be "mouseup" or it might be "keyup" or ... You just know (or at least you hope!) that ev.type is *ONE* of the properties of the tool object. You *COULD* do Code:
eval( "tool." + ev.type );So, realistically, the best way *IS* to use simply Code:
tool[ ev.type ];Code:
switch ( ev.type )Code:
tool[ev.type]( ev ); |
| All times are GMT +1. The time now is 07:42 AM. |
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.