user999970
user999970

Reputation: 1

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?

Upvotes: 0

Views: 44

Answers (2)

John Fisher
John Fisher

Reputation: 22719

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

Upvotes: 0

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

This is called Closure.

There is a lot to read on this.

Upvotes: 1

Related Questions