本文介绍了Python类的“类”在Javascript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在Javascript中使用类似于Python中的类。使用下面列出的Python类和函数:

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

函数foo将被调用 one.foo (bar)

JS等效项是什么?我怀疑这将是这样的:

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
    }
};

谢谢。

推荐答案

在Javascript中创建类的本地方法是首先定义构造函数:

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

function MyClass() {
}

和原型:

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

然后你可以创建MyClass的实例:

Then you can create instance of MyClass:

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

添加静态方法:

MyClass.staticMethod = function() {};

MyClass.staticMethod();

扩展MyClass:

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

var object = new SubClass;
object.foo();
object.bar();

这篇关于Python类的“类”在Javascript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 18:35