开发者

what's the line meaning in javascript

function bind( obj, type, fn ) {
    if ( obj.attachEvent ) {
        obj['e'+type+fn] = fn;
        obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
        obj.attachEvent( 'on'+type, obj[type+fn] );
    } else
        obj.addEventListener( type, fn, false );
}

i am new to javascript, the above code is from the internet. i don't understand the above function well, expect someone can explain it to me. thank you, why it declare three argument(obj, type, fn). obj['e'+type+fn] what's开发者_StackOverflow this line meaning.


obj['e'+type+fn] accesses the attribute of obj with the name 'e' + type + fn.

With type='abc' and fn='foo', it would access obj.eabcfoo.


In JavaScript, there is an equivalence between objects and hash sets. Thus, saying obj['abc']=123; is equivalent to obj.abc=123. By using the hash set notation, you can build your property names dynamically - in this case by concatenating 'e' with the values of type and fn.


This function accepts three parameters:

  1. An object (specifically, a DOM node) that it will set an event handler on
  2. The event which will have the handler attached to it (e.g. "click")
  3. A function which is the event handler

It then creates two "helper" functions and uses them to assign the event handler:

obj['e'+type+fn] = fn; // helper #1
obj[type+fn] = function(){obj['e'+type+fn]( window.event );} // helper #2
obj.attachEvent( 'on'+type, obj[type+fn] ); // assigns event handler

The lines with the obj[something] syntax are simply accessing (getting/setting) a member of obj whose name is variable. For example, this:

var name = "alert";
window[name]();

does the same thing as this:

window.alert();

However, in the first case you have the value of name coming from a variable instead of being hardcoded.


It's used to attach events to objects dynamically.

For example to assign click event to some element:

var oDiv = document.getElementById("myDiv");
bind(oDiv, "click", MyClickHandler);

This will bind the click event of element with ID myDiv and execute function called MyClickHandler when that element is clicked.

Working example: http://jsfiddle.net/sDwvP/

These days such things are considered "old school" or obsolete, you better use full scale library like jQuery.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜