Python-Like “Classes” in Javascript

2019-03-31 02:28发布

问题:

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.

回答1:

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();


回答2:

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



回答3:

Have a look at this link. There a different ways to do OO programming in Javascript. The details are too much to be explained here.

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

If you want to do real heavy OO programming, I would recommend to have a look at Coffee Script.



回答4:

Javascript doesn't really have classes. What it has is prototypes -- an instance of an object that is used as a template for new objects.

The way you've created your object is to use a literal constructor. It's succinct, but suffers that it cannot be added to or use complicated statements in its construction.

Another way is like so:

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

And a new instance is created like this:

var obj = new SomeClass(15);

This enables you to use conditional logic, for loops and other more complicated programming techniques in construction of your object. However, we can only add instance fields and not 'class' fields. You add class fields my modifying the prototype of your object creator function.

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

This gives a more complete overview of object creation and prototypes in Javascript.