Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Prototype Example

I am trying to use the prototype feature with example code that I have from another site.

I have simplified the code and listed it below. When I use it I get the following error: TypeError: this.createChart is not a function. I do not get this error on jsfiddle, only when I am trying to implement the code my site.

My working jsfiddle is here: http://jsfiddle.net/56vjtv3d/76

Any suggestions? Thanks!

 function Meteogram(A,B) {
      this.A = A;
      this.B = B;
      this.createChart(); 
    }

    Meteogram.prototype.createChart = function() {
      alert('test');
      //Will do other stuff here
    };
like image 775
Aquabug222 Avatar asked Dec 05 '25 05:12

Aquabug222


1 Answers

This code works fine, you are probably not initializing your object/s correctly

Your Meteogram function is known as "Object Constructor" and its usefull to create several similar objects, and to create new objects from this constructor you need to use the new keyword

We already have this:

function Meteogram(A,B) {
    this.A = A;
    this.B = B;
    this.createChart(); 
}

Meteogram.prototype.createChart = function() {
    alert('test');
    //Will do other stuff here
}

now..

This will work:

var m = new Meteogram('a', 'b');
// Now m is an instance of Meteogram !!

This won't:

var m = Meteogram('a', 'b');
// Uncaught TypeError: this.createChart is not a function(…)
like image 138
Aramil Rey Avatar answered Dec 07 '25 19:12

Aramil Rey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!