【问题标题】:Call this (public) function inside private function在私有函数中调用这个(公共)函数
【发布时间】:2012-12-06 02:00:03
【问题描述】:

我有以下 javascript:(JSFiddle)

$(function () {
    function Cat()
    {  
        this.Meow = function (sound) {
            alert("Meow: " + sound);
        }

        this.Kick = function () {
            MakeNoise();    
        }

        var MakeNoise = function () {
            Meow("noise");
            //Cat.Meow("noise");
            //self.Meow("noise");
            //this.Meow("noise");                      
        }        
    }

    var c = new Cat();
    c.Kick();
});​

当我调用 Kick 函数时,我收到错误“未定义喵”(我在 MakeNoise 函数中尝试的四件事中的任何一件)。

我也尝试过这样的原型设计,但这给了我同样的错误:

Cat.prototype.Meow = function (sound) {
    return this.Meow(sound);    
}

我确信这有一个非常简单的解决方案,但我不知道如何成功调用“Cat”类的Meow 函数。我该怎么做?

顺便说一句,这种架构是否有意义?我的意图是将KickMeow 作为公共函数,将MakeNoise 作为私有函数。

【问题讨论】:

标签: javascript


【解决方案1】:

保存一个引用对象,以便您可以在MakeNoise 函数中使用它。

$(function () {
    function Cat()
    {  
        var self = this;
        this.Meow = function (sound) {
            alert("Meow: " + sound);
        }

        this.Kick = function () {
            MakeNoise();    
        }

        var MakeNoise = function () {
            //Meow("noise");
            //Cat.Meow("noise");
            self.Meow("noise");
            //this.Meow("noise");                      
        }        
    }

    var c = new Cat();
    c.Kick();
});​

http://jsfiddle.net/mowglisanu/7XEYD/3/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 2013-05-01
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 2015-04-02
    相关资源
    最近更新 更多