我是 javascript 新手..我正在尝试在 JS 中创建一个私有(private)函数并在外部访问它..这是我的代码
function Person(name, gender) {
this.name = name;
this.gender = gender;
//the private function
function aFunction(arg1) {
alert("anything");
}
}
var person = new Person("bob", "M");
person._privates['aFunction']();
最佳答案
I am trying to make a private function in JS and access it outside
首先,这条语句是oxymoron ,因为根据定义,私有(private)函数对于作用域来说是私有(private)的,因此不应该在外部访问。
如果您的意思是您想要访问在 Person
内部定义的方法,那么 -> 尝试使您的 Person
类具有_privates
成员为
function Person(name, gender){
this.name = name;
this.gender = gender;
this._privates = {}; //new property added to access private functions
//the private function
this._privates.aFunction = function (arg1){
alert("anything");
};
}
关于javascript - 尝试在JS中创建私有(private)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35766133/