开发者

javascript call a privileged method

开发者 https://www.devze.com 2023-01-01 03:20 出处:网络
If I call the killSwitch() outside the onkeypress, I\'ll cause an error. But inside the onkeypress function, I worked just fine.

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(); }  
开发者_Go百科    this.killSwitch = function(){ alert('hello world'); }  
}

var myClass = new ClassA();


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();


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消