OOP. Calling methods from within methods

前端 未结 4 2084
一生所求
一生所求 2021-01-19 19:30

How do I call class methods from functions within the class? My code is:

var myExtension = {

    init: function() {
        // Call onPageLoad
    },  

            


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-19 20:24

    Assuming that you have called init like this:

    myExtension.init();
    

    then it should be:

    init: function() {
        // before
        this.onPageLoad();
        // after
    }
    

    But in Javascript functions are not actually bound to objects and you can call any function on any other object, like this:

    myExtension.init.call(anotherObject); // or
    myExtension.init.apply(anotherObject);
    

    In this example this within init would be anotherObject, which doesn't have onPageLoad defined. If you want to support this kind of usage you'll have to manually reference the initial object:

    init: function() {
        // before
        myExtension.onPageLoad();
        // after
    }
    

提交回复
热议问题