0

I have an constructor object like this .

var Cons = function(me){
  this.name= me;
  this.ele = document.getElementById("element");
  this.ele.addEventListener("click",this.fnClick,false);
}

and some methods extended as prototypes

 Cons.prototype.getme= function(){
     return this.me;
  }
  Cons.prototype.fnClick= function(){
      alert(this.getme())
  }
 var initZ = new Cons("test");

So my problem is when im "fcClick" is executed as a bind function "this" will refer to the binded HTML element , not the current instance Object,

So how can i pass the reference of "this" in "fnClick" ..?

jsfiddle link

0

2 Answers 2

2

Use this.fnClick.bind(this) or, for browsers that do not support bind:

var Cons = function(me){
  this.name= me;
  this.ele = document.getElementById("element");

  var self = this;
  function handler() {
    self.fnClick(arguments);
  }
  this.ele.addEventListener("click", handler, false);
}

See http://jsfiddle.net/Fy5ZV/1/ (with getme() returning this.name)

Sign up to request clarification or add additional context in comments.

2 Comments

ys actualy i want it like with a self reference , but i cant bind a private fn handler , since i need to make a removeEvent in some other function, and i cant declare just public functions, its a part of a framework..
You can implement a shim for Function.prototype.bind, see here, the Compatibility section.
1

You can use bind()...

var Cons = function(me){
  this.name= me;
  this.ele = document.getElementById("element");
  this.ele.addEventListener("click",this.fnClick.bind(this),false);
}

This will guarantee that the ThisBinding will be set to the calling environment's this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.