user229738
user229738

Reputation: 23

javascript call a privileged method

If I call the killSwitch() outside the onkeypress, I'll cause an error. But inside the onkeypress function, I worked just fine. Why?

// this works fine
var ClassA = function()  
{  
    var doc = document;
// killSwitch();

    doc.onkeypress = function(e){ killSwitch(); }  
    this.killSwitch = function(){ alert('hello world'); }  
}

var myClass = new ClassA();

Upvotes: 1

Views: 512

Answers (2)

Josh
Josh

Reputation: 11070

Try:

var ClassA = function()  
{  
    var doc = document;
    var killSwitch = function(){ alert('hello world'); };
    killSwitch();

    doc.onkeypress = function(e){ killSwitch(); }  
    this.killSwitch = killSwitch  
}

var myClass = new ClassA();

This way you define the killSwitch function inside the ClassA function, creating a closure, and it is available both within and outside the class.

Upvotes: 0

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827744

You can't call killSwitch because you defined the method as a property of the object instance (this.killSwitch).

You can't use this inside the keypress event, because it will refer to the document, you have to store the this value:

var ClassA = function() {  
    var doc = document, 
              instance = this; // store reference to `this`

    doc.onkeypress = function(e){ instance.killSwitch(); }; 
    this.killSwitch = function(){ alert('hello world'); };
}

var myClass = new ClassA();

Upvotes: 4

Related Questions