Nodejs 后端程序 class 怎么实现私有方法 - CNode技术社区

Nodejs 后端程序 class 怎么实现私有方法
发布于 7 年前 作者 RooQs 4865 次浏览 来自 问答

搞了半天不知道怎么办 自己写的代码看下 可行吗

"use strict"

const testF=function (){ console.log(this.name) }

class Test{

constructor(name){
 this.name=name
}
test(){
 testF.bind(this)()
}

}

let t=new Test(‘小明’)

t.test()

9 回复

function testF(){ function xx(){}; } testF.prototype.a = function(){ this.xx(); }; module.exports = testF; 这里面xx()是私有方法,a()是公共方法。

ES6不提供私有方法的

学习下 markdown 排版吧。。。

private 的提案还没落地,现在的话一般用 Symbol 来模拟

const _hide = Symbol('hide');
class Test {
 [_hide] () {
 console.log('I\'m private');
 }
 sayHi() {
 this[_hide]();
 }
}

module 不导出的就是私有方法

typescript 了解下

用Proxy,调用时检测属性

来自酷炫的 CNodeMD

const privateVar = Symbol.for('pravite#var')
回到顶部

AltStyle によって変換されたページ (->オリジナル) /