可以在 Javascript 类中返回一个对象吗?

MHS*_*MHS 1 javascript class

如果在定义类构造函数时返回一个对象会发生什么?我可以使用它来确保安全并避免访问类方法并且......?

例如我有下面的代码:

class X {
  y = ''
  x = 0

  constructor(
    p1,
    p2,

  ) {
    this.p1 = p1
    this.p2 = p2
    return {
      getp1: this.getp1
    }
  }
 getp1 = () => this.p1
}

let x = new X("fo", "bar")
console.log(x.p1) // will be undefined
console.log(x.getp1() ) // will be "fo"
Run Code Online (Sandbox Code Playgroud)

如您所见,x.p1无法直接访问,但我可以p1通过getp1方法获得。我可以在 javascript 中使用它private和方法吗?public

小智 5

这将是一个更好的方法。

您可以使用#将属性或方法设置为“私有”,这意味着它只能由该类内部的方法或属性访问。下面的代码演示了它的用法

class Test {
    #privateValue;
    constructor() {
        this.#privateValue = 10;
    }

    test() {
        return this.#privateValue;
    }
}

const test = new Test();
console.log(test.privateValue)
console.log(test.test())
Run Code Online (Sandbox Code Playgroud)