Javascript TypeError: this.init 不是一个函数错误

3
这是我的JavaScript代码。
    Html5Template_300x250 = function(config) {
       this.config = config;
        var self = this;
        this.init();       
        Html5Template_300x250.prototype = {
            // Function That Creates Element Var
            d: function(id) {
                return document.getElementById(id);
            },

            // Initialize DCO HTML5 template
            init: function() {
                alert("test1");
                this.startAd();

            },

            startAd: function() {
                alert("test2");

            }

        };
    }

我正在创建一个HTML文件,可以使用以下方法:

 var sr_Config = {            
            bgColor:'#fff',
            ctaText:'Learn More',
            border: 'true'
        };


        var Html5Template = new Html5Template_300x250(sr_Config);

但我遇到了错误

TypeError: this.init不是一个函数this.init();

我不确定这里出了什么问题,我也尝试了self.init(),但仍然无法工作。

我是JavaScript的新手,正在学习JavaScript中的面向对象编程,如果有人能告诉我在这里做错了什么,那就太好了。先谢谢了。


1
你应该在使用/调用之前定义init方法。 (所以将对init函数的调用放在init函数本身下面) - roel
1个回答

3

您需要将方法分配给原型属性(至少这是我做的方式)。您还需要在调用函数之前这样做。

Html5Template_300x250 = function(config) {
    this.config = config;
    var self = this;

    Html5Template_300x250.prototype.d = function(id) {
        return document.getElementById(id);
    };

    Html5Template_300x250.prototype.startAd = function() {
        alert("test2");
    };

    // Initialize DCO HTML5 template
    Html5Template_300x250.prototype.init = function() {
        alert("test1");
        this.startAd();
    };

    self.init();
}

另一种不使用prototype的方法是这样的:

Html5Template_300x250 = function(config) {
    this.config = config;
    var self = this;

    this.d = function(id) {
        return document.getElementById(id);
    };

    // and so on..

    self.d('myid');
}

请查看这个带有一些示例代码的工作演示

关于JS中的OOP,JS-Guru Douglas Crocford 提供了更多有趣的阅读内容;)


谢谢,但我有点困惑,我该如何修复我的当前代码?我需要添加什么?你能解释一下吗?谢谢。 - user3754380
请查看更新的答案。也许你需要做一些调整,但基本上就是这样工作的... - nozzleman
我还添加了一种更简单的方法(在我看来)。如果你对这个主题感兴趣,可以查看我在答案中提供的链接。 - nozzleman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接