【问题标题】:Using an object as a method's argument in es 6在 es 6 中使用对象作为方法的参数
【发布时间】:2018-11-02 04:31:49
【问题描述】:

我试图将一个新的Point 对象作为plus 方法的参数,然后添加以返回该值。 Point p 在 java 中是正确的,但在 javascript 中是不正确的。

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    plus(Point p) {
        console.log(p.a);
        return new Point(p.a + this.x, p.b + this.y);
    }
}

console.log(new Point(1, 2).plus(new Point(2, 1)));

// → Point{x: 3, y: 3}

【问题讨论】:

  • Point p 不是有效的 JS,您使用的是类型提示,还是像 typescript 这样的编译语言?
  • JavaScript 中的参数不输入;写plus(p) { ... }
  • 不就是一个错字吗? p.x + this.x, p.y + this.y
  • Java 之于 Javascript 就像汽车之于地毯一样。在编写 Javascript 时忘记任何关于 Java 的知识。

标签: javascript class object ecmascript-6


【解决方案1】:

您需要在没有类型的情况下采用正确的属性和参数。

class Point {

    constructor (x, y) {
        this.x = x;
        this.y = y;
    }

    plus (p) {
        return new Point(p.x + this.x, p.y + this.y);
    }
}

console.log(new Point(1, 2).plus(new Point(2, 1)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 2020-06-05
    相关资源
    最近更新 更多