Javascript定义私有变量
问题描述:
我想用c构建一个类似于javascript的类,主要问题是private
属性。Javascript定义私有变量
var tree = {
private_var: 5,
getPrivate:function(){
return this.private_var;
}
};
console.log(tree.private_var);//5 this line want to return unaccessible
console.log(tree.getPrivate());//5
,所以我想从tree.private_var
检测接入和返回unaccessible
,并this.private_var
回报5
。
我的问题是:有没有什么办法可以在javascript中设置私有属性?
编辑:我看到这样
class Countdown {
constructor(counter, action) {
this._counter = counter;
this._action = action;
}
dec() {
if (this._counter < 1) return;
this._counter--;
if (this._counter === 0) {
this._action();
}
}
}
CountDown a;
a._counter
是无法访问? 但
答
定义tree
的功能,而不是JavaScript对象,通过var
关键字定义的函数私有变量,通过this.
关键词界定公共取得功能和使用功能
var Tree = function(){
var private_var = 5;
this.getPrivate = function(){
return private_var;
}
}
var test = new Tree();
test.private_var; //return undefined
test.getPrivate(); //return 5
在创建新实例ES6,你能做到这一点,但它不支持IE所以我不建议
class Tree{
constructor(){
var private_var =5;
this.getPrivate = function(){ return private_var }
}
}
var test = new Tree();
test.private_var; //return undefined
test.getPrivate(); //return 5
可是什么?看起来你没有完成这个问题。 – Barmar