简体   繁体   English

更改 Nodejs 中类的行为 (javascript)

[英]Change the behavior of classes in Nodejs (javascript)

I come from python where any class can have functions like __add__ , __str__ , ecc... to change the behavior of sum, printing, ecc... of the class.我来自 python,其中任何类都可以具有__add____str__ 、 ecc... 之类的函数来更改类的 sum、printing、ecc... 的行为。

Is there an equivalent in Javascript? Javascript 中是否有等价物?

For example:例如:

class A:
    def __init__(self, a):
        self.a = a
    def __add__(self, other):
        return self.a + other.a

How would this script be in javascript?这个脚本在javascript中如何?

What you are looking for is called "operator overloading".您正在寻找的称为“运算符重载”。 Python uses magic methods for that. Python为此使用了魔术方法。 Javascript unfortunately does not support this kind of behavior.不幸的是,Javascript 不支持这种行为。 This question has been answered before, please take a look at this answer .这个问题之前已经回答过了,请看一下这个答案

it would be the same, just in JavaScript :P它会是一样的,只是在 JavaScript 中:P

class A {
  constructor(a) {
    this.a = a
  }
  add(other) {
    return this.a + other.a
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM