简体   繁体   English

从另一个类的公共方法中调用一个类的公共方法

[英]Call a public method of a class, from a public method of another class

How can I call methodOne from methodTwo ? 如何从methodTwo调用methodOne?

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? 如何从methodTwo调用methodOne?

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: 要使其在methodTwo的范围内已知,请将其作为参数传递给函数:

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

…

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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