Python-like "classes" in Javascript

I was wondering how one could make โ€œclassesโ€ look like classes in Python in Javascript. Take the Python classes and functions listed here:

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

The foo function will be called using one.foo(bar) .
What is the equivalent of JS? I suspect it will be something like this:

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

Thanks.

+4
source share
4 answers

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

 function MyClass() { } 

and prototype:

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

Then you can create an 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(); 
+9
source

Check out this link . There are various ways to program OO in Javascript. There are too many details to explain here.

If you are serious about Javascript programming, you should read this book .

If you want to do really hard OO programming, I would recommend looking at Coffee Script .

+6
source

Classy is a JavaScript library that tries to inject classes like Python into JavaScript.

+6
source

Javascript really has no classes. What he has is prototypes - an instance of an object that is used as a template for new objects.

The way you created your object is to use a constructor literal. It is concise, but suffers from the fact that it cannot be added or use complex instructions in its design.

Another way:

 function SomeClass(value) { if (value < 0) { this.field = -1; } else { this.field = value; } } 

And a new instance is created as follows:

 var obj = new SomeClass(15); 

This allows you to use conditional logic, loops, and other more complex programming methods when building your object. However, we can only add instance fields, not "class" fields. You add class fields by changing the prototype functions of your creator object.

 MyClass.prototype.fieldSquared = function () { return this.field * this.field; } 

This is a more complete overview of creating objects and prototypes in Javascript.

+2
source

All Articles