【问题标题】:Call a public method of a class, from a public method of another class从另一个类的公共方法调用一个类的公共方法
【发布时间】:2013-09-11 16:28:08
【问题描述】:

如何从 methodTwo 调用 methodOne

有没有安全正确的方法?

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

【问题讨论】:

  • 您忘记了 IEFE 中的构造函数 return,并且在定义它们之前就使用了它们。
  • 这些方法是实例方法classTwo 实例如何知道classOne 实例来调用它的方法?
  • @Bergi 我更新了示例!

标签: javascript class oop methods


【解决方案1】:

如何从 methodTwo 调用 methodOne?

您需要访问要调用该方法的实例(您也可以从原型中获取它并应用于某个任意对象,但我想这不是您想要的)。要使其在methodTwo 范围内为人所知,请将其作为参数传递给函数:

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

…

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

【讨论】:

  • 另外,他可以在methodTwo内创建实例。
猜你喜欢
  • 2011-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多