简体   繁体   中英

Call a public method of a class, from a public method of another class

How can I call methodOne from methodTwo ?

Is there a safe and correct way?

$(document).ready(function () {
    var classOne = new ClassOne();
    var classTwo = new ClassTwo();
});

var ClassOne = (function (window, document, Math, undefined) {

    function ClassOne () {
    }

    ClassOne.prototype = {
        methodOne: function () {
            console.log('method one');
        }
    };

    return ClassOne;
})(window, document, Math, undefined);

var ClassTwo = (function (window, document, Math, undefined) {

    function ClassTwo () {
    }

    ClassTwo.prototype = {
        methodTwo: function () {
            // how to call?
            // classOne.methodOne()
        }
    };

    return ClassTwo;
})(window, document, Math, undefined);

How can I call methodOne from methodTwo?

You need to access the instance on which you want to call the method (you could as well get it from the prototype and apply on some arbitrary object but I guess that's not what you want). To make it known in the scope of the methodTwo , pass it as a parameter to the function:

ClassTwo.prototype.methodTwo = function (one) {
    one.methodOne();
};

…

var classOne = new ClassOne();
var classTwo = new ClassTwo();
classTwo.methodTwo(classOne);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM