function Cl(){ this.name=100; this.view=function(){ input=document.createElement('input'); input.name='inputs'; input.addEventListener('click',function(){console.log(this.name)}) document.body.appendChild(input); } } obj=new Cl; obj.view(); 

Help call console.log (this.name) to get 100; You need to refer to the object created by the constructor. Consider all the options. The more the better. Thanks.

    2 answers 2

    or so:

     input.addEventListener('click',function(){ console.log(this.name) }.bind(this)) 

    or so:

     function Cl(){ var self = this; this.name=100; this.view=function(){ ... input.addEventListener('click',function(){console.log(self.name)}) ... } } 
    • Grateful. Who will read - learn.javascript.ru/… - zloctb
    • one
      it is generally canonically bind here:! function () {var _slice = Array.prototype.slice Function.prototype.bind = function (context) {var args = _slice.call (arguments, 1), func = this; return function () {return func.apply (context, args.concat (_slice.call (arguments, 0))); }}} () - Specter
    • It is possible without .bind(this) you already pass the context when you hang the handler on the element. - lampa
    • in general, the context is determined during a function call, not its definition, or I misunderstood you - Specter
    • one
      that's it, the vehicle wanted the context not to be the element on which the handler was hung, but obj - Specter
     input.addEventListener('click',function(t){return function(){console.log(t.name)}}(this)) 
    • Grateful - zloctb