最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to call "class method" from outside class in JavaScript? - Stack Overflow

programmeradmin4浏览0评论

I've got some code in JavaScript and I'm looking to trigger a ViewModel method using a keyboard shortcut. What is the correct syntax? Here's my code:

document.addEventListener('keydown', function(event) {
    if (event.keyCode==27){
        ViewModel.escapePressed();
    }
}, true);

function ViewModel() {
    this.escapePressed=function(){
        // Code
    };
}

I've got some code in JavaScript and I'm looking to trigger a ViewModel method using a keyboard shortcut. What is the correct syntax? Here's my code:

document.addEventListener('keydown', function(event) {
    if (event.keyCode==27){
        ViewModel.escapePressed();
    }
}, true);

function ViewModel() {
    this.escapePressed=function(){
        // Code
    };
}
Share Improve this question asked Nov 20, 2015 at 23:15 RogareRogare 3,2744 gold badges30 silver badges54 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

If you are going to use that style of class, then you must first make an instance of it.

var a_view_model = new ViewModel();
a_view_model.escapePressed();

… but if you just want to have a static method, then you probably shouldn't be using a constructor function in the first place

var view_model = {
    escapePressed: function () { };
}

and:

view_mode.escapePressed();
发布评论

评论列表(0)

  1. 暂无评论