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.
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();
Classy is a JavaScript library that tries to bring Python-like classes to JavaScript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With