Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-Like "Classes" in Javascript

I was wondering how one would go about making "classes" similar to those in Python in Javascript. Take the Python classes and functions listed here:

class one:
    def foo(bar):
        # some code

The function "foo" would be called with one.foo(bar).
What would the JS equivalent be? I suspect it would be something like this:

var one = {
    foo: function(bar) {
        // JavaScript
    }
};

Thanks.

like image 998
terrygarcia Avatar asked Nov 28 '22 18:11

terrygarcia


2 Answers

The native way to create classes in Javascript is to first define the constructor:

function MyClass() {
}

and a prototype:

MyClass.prototype = {
    property: 1,
    foo: function(bar) {
    }
};

Then you can create instance of MyClass:

var object = new MyClass;
object.foo();

Add static methods:

MyClass.staticMethod = function() {};

MyClass.staticMethod();

Extend MyClass:

function SubClass() {
}
SubClass.prototype = new MyClass;
SubClass.prototype.bar = function() {
};

var object = new SubClass;
object.foo();
object.bar();
like image 79
Arnaud Le Blanc Avatar answered Dec 06 '22 18:12

Arnaud Le Blanc


Classy is a JavaScript library that tries to bring Python-like classes to JavaScript.

like image 43
icktoofay Avatar answered Dec 06 '22 18:12

icktoofay