Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

typescript class定义私有方法

image.png
image.png

ts 中的class如何实现以上效果
类中有私有方法a
a可以被实例上的方法引用
a可以引用实例上的属性
打印实例方法a不可见


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

如果你需要 es 中的真正的私有属性,而非 ts 的假私有属性,可以这样写:

class Test {
    #a = () => console.log(1)

    public b() {
        this.#a();
    }
}

如果你需要支持低版本的 js,而只是希望这个属性不可见(其实还是可以访问的),可以将这个数值设置为不可枚举。

function Test() {}

Object.defineProperty(Test.prototype, "a", {
  enumerable: false,
  writable: true,
});

Test.prototype.a = function() {
  console.log(111)
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...