JavaScript 中的“私有(private)变量”是什么意思? javascript 中没有声明“私有(private)变量”。
所以我们通常使用“_”或闭包。
在这一点上,我很好奇“关闭”。 我从另一个网站得到了例子。
function createAnimal(name, job) {
// "Private" variables here
let _name = name;
let _job = job;
// Public variables here
return {
// Getter Methods
getName() {
return _name;
},
getJob() {
return _job;
},
// Setter Methods
setName(newName) {
_name = newName;
},
setJob(newJob) {
_job = newJob;
}
};
}
上面的例子
我们可以更改 setName 的 _name '私有(private)变量'。
真实
“私有(private)变量”意味着我们不能访问变量?还是常量?
最佳答案
希望这对你有帮助:
Private members are made by the constructor. Ordinary vars and parameters of the constructor become the private members.
function Container(param) {
this.member = param;
var secret = 3;
var that = this;
}
This constructor makes three private instance variables: param, secret, and that. They are attached to the object, but they are not accessible to the outside, nor are they accessible to the object's own public methods. They are accessible to private methods. Private methods are inner functions of the constructor.
function Container(param) {
function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}
this.member = param;
var secret = 3;
var that = this;
}
The private method dec examines the secret instance variable. If it is greater than zero, it decrements secret and returns true. Otherwise it returns false. It can be used to make this object limited to three uses.
By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.
Private methods cannot be called by public methods. To make private methods useful, we need to introduce a privileged method.
引用:Read more
关于javascript - javascript中的私有(private)变量意味着,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59150578/