在模块模式中添加原型方法 - 错误:不是函数

时间:2015-08-25 16:17:10

标签: javascript prototype module-pattern

我正在尝试使用模块模式进行简单的javascript练习,但也希望集成原型方法。在模块外部调用时,即使在创建对象之后,也找不到原型方法。我错过了什么?在模块模式中使用原型方法是否会破坏模块模式的目的?

var BroChart = (function(){
    "use strict";

    //revealing module pattern
    return {
        Point: Point,
        Series: Series,
        Chart: Chart,
        addPoint: addPoint,
        addPoints: addPoints,
        addSeries: addSeries        
    };

    function Point(x, y){
        this.coordinates = [x, y];
    }

    function Series(label){
      this.pointArray = [];
      this.label = label;
    }

    // method to add single point
    function addPoint(series, point) {

      if (point instanceof Point) {
        series.pointArray.push(point.coordinates);      
      } else {
        console.log('Error: not a valid point');
      }

    }

    // method to add array of points
    function addPoints(series, points) {

      points.forEach(function(point) {
        if (point instanceof Point) {
          series.pointArray.push(point.coordinates);      
        } else {
          console.log('Error: not a valid point');
        }        
      });

    }  


    function Chart(title, data, type){
      this.title = title;
      this.data = data;
      this.type = type;      
      this.printSeries = function() { _printSeries(this); };
    }  

    //prototype method in question
    Chart.prototype.printSeries2 = function() {
        console.log(this.title + ' Chart');
        console.log('Type: ' + this.type);
        console.log('Data Points: ' + this.data.pointArray);
    };

    function addSeries(chart, series) {
      if (series instanceof Series) {
        chart.data.push(series.pointArray);
      } else {
        console.log('Error: not a valid series');
      }
    }

    function _printSeries(chart) {
        console.log(chart.title + ' Chart');
        console.log('Type: ' + chart.type);
        console.log('Data Points: ' + chart.data.pointArray);
    }


})();

    var broSeries = new BroChart.Series('Protein vs. Sick Gainz');
    var firstPoint = new BroChart.Point (343, 21);
    var secondPoint = new BroChart.Point (2, 11);
    var thirdPoint = new BroChart.Point (54, 241);
    var fourthPoint = new BroChart.Point (76, 988);

    BroChart.addPoint(broSeries, firstPoint);
    BroChart.addPoints(broSeries, [secondPoint, thirdPoint, fourthPoint]);

    var Bro = new BroChart.Chart('Protein vs. Sick Gainz', broSeries, 'line');

    Bro.printSeries(Bro);
    //problematic prototype method call
    Bro.printSeries2();

1 个答案:

答案 0 :(得分:1)

你应该在闭包结束时创建对象

Chart.prototype.printSeries2 = function(){...}

编辑:解释是YTPlayerView是一个声明,并没有因为最高回报而被执行。

看到它在这里运行:https://jsfiddle.net/f8ednmw2/