Search code examples
javascriptprocessing.js

How do I make a JavaScript (processing.js) class on KhanAcademy?


In the coding section of Khanacademy, I'm making a project in JavaScript (which is modified Processing.js here), and it gives errors for both notations of classes:

function Foo(bar) {
    this.bar = bar;
}

Foo.prototype.baz = function() { }

and

class Foo {

constructor(bar) {
    this.bar = bar;
}

baz() { }

The top one seemed mostly compatible, but the code wouldn't compile, saying "If you want to define a function, you should use 'var Foo = function() {};' instead".

Does anyone know how to make a class on this platform?


Solution

  • Khan Academy is good for learning the basics, but like you said it uses a modified version of Processing.js, which means that it chokes on syntax that should be valid.

    If you really really need to use a class in Khan Academy, after playing around a bit, this example seems to work:

    var Foo = function(x) {
        this.x = x;
    
        this.printX = function(){
          println('x: ' + this.x);  
        };
    };
    
    draw = function() {
      var myFoo = new Foo(42);
      myFoo.printX();
    };
    

    But you're probably better off using something like P5.js or even vanilla JavaScript.