0
--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?

2 Answers2

1

This is called Closure.

There is a lot to read on this.

Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
0

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

Community
  • 1
  • 1
John Fisher
  • 22,355
  • 2
  • 39
  • 64