1

i want to call variable "info" when user click on div

the code supposed to print "success"

but its print "undefined"

html

<div id="container" style="width: 100px; height: 100px; border: solid black 1px">

javascript

window.onload = function(){

var Controller = function(){

    this.info = '  success  ';

    this.listener = function(){
        alert( this.info );
    }

    this.set = function( ele ){
        ele.onclick = this.listener;
    }
}


var target = document.getElementById('container');
var controller = new Controller();
    controller.set( target );



}

jsfiddle

my goal

  • i need to call variable "info" inside Controller listener
  • i need to give action click inside Controller set

my problem is inside function "listener",

keyword "this" refer to div element, not class Controller

how to call variable info inside function "listener" ?

2 Answers 2

3

Try

var Controller = function(){
  var self = this; // Add this
  this.info = '  success  ';
  this.listener = function(){
    alert( self.info ); // Modify here
  }
....
Sign up to request clarification or add additional context in comments.

Comments

0

You can use bind to bind the function to the right this:

ele.onclick = this.listener.bind(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.