简体   繁体   中英

can someone tell me how/why this works in ff and ie

--script--
function myalert(name){
  var obj=this;
  obj.run=run;
  function run(){
    alert(name);
  }    
  div=document.createElement('div');
  div=document.body.append(div);
  txt=document.createTextNode('alert');
  div.appendChild(txt);
  //**
  div.onclick=function(){ obj.run(); }
  //**
}
--html--
<div onclick="myalert('mee');">matt</div>

the thing i find strange, is the obj.run() is called outside the function, from a dom element, and the function parameter is also preserved

also are there any pitfalls to this method?

This is called Closure .

There is a lot to read on this.

You're looking for an understanding of "lexical scope". Here's one explanation: What is lexical scope?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM