如何从对象内部调用方法?

时间:2014-12-18 00:43:26

标签: redactor

我试图修改我为Redactor找到的插件,以使其使用最新版本,但我对JavaScript的无知使我无法使其正常工作。

if (!RedactorPlugins) var RedactorPlugins = {};

RedactorPlugins.wordcount = function() {
    return {
        init: function() {
            var self = this;
            var $box = $(this.core.getBox());
            if ($box.length>0) {
                if ($box.find('.redactor-wordcount').length==0) {
                    var $wordcount_holder = $('#counter');

                    $box.on('keyup', function () {
                        $wordcount_holder.text('Words: ' + self.count());
                    });

                    $wordcount_holder.text('Words: ' + self.count());
                }
            }
        },

        count: function() {
            var html = this.get(),
                text = $(html).text().replace(/\t+/g, " ").replace(/\n/g, " ").replace(/\s+/g, " ");
            return text.split(' ').length - 1;
        }
    };
};

当我加载页面时,输出错误Uncaught TypeError: undefined is not a function。它指的是count函数。

我的印象是这种语法:

return {
...
}

导致返回一个对象,但由于某种原因,调用self.count()会导致抛出上述错误。

如何从count函数中调用init函数?

编辑:顺便说一句,以下是应该如何定义Redactor插件(对于新版本的软件):

if (!RedactorPlugins) var RedactorPlugins = {};

RedactorPlugins.myplugin = function()
{
    return {
        myMethod: function()
        {
            // your code
        }
    };
};

1 个答案:

答案 0 :(得分:1)

我怀疑Redactor正在调用init()this指向某个与您预期不同的对象。要调用count(),您可能需要在return语句之前声明它,以便在多个位置使用它。

RedactorPlugins.wordcount = function() {

    // Declare count here, then remove 'this.' when you call it (see my comments below)
    var count = function() {
        var html = this.get(),
            text = $(html).text().replace(/\t+/g, " ").replace(/\n/g, " ").replace(/\s+/g, " ");
        return text.split(' ').length - 1;
    }

    return {
        init: function() {
            var self = this;
            var $box = $(this.core.getBox());
            if ($box.length>0) {
                if ($box.find('.redactor-wordcount').length==0) {
                    var $wordcount_holder = $('#counter');

                    $box.on('keyup', function () {
                        // Note the lack of 'this' here...
                        $wordcount_holder.text('Words: ' + count());
                    });
                    // ... and here
                    $wordcount_holder.text('Words: ' + count());
                }
            }
        },

        // Pass your count function as part of the return value
        // if you still want it to be accessible to whoever uses
        // the return value of this function.
        count: count
    };
};