这是将变量设置为私有(private)的正确方法吗?
function test(a, b){
let aa = a
let bb = b
return {
getA: () => {
return aa
},
getB: () => {
return bb
}
}
}
现在我无法直接访问 aa
和 bb
。如果我将 this
关键字放在变量前面,它会被接受为对象吗?我知道 JavaScript 中的函数是对象,但它变得更像对象语法。我对所有 JavaScript 选项感到很困惑。似乎任何事情都没有约定俗成。
this
类型:
function test(a, b){
this.aa = a
this.bb = b
return {
getA: () => {
return this.aa
},
getB: () => {
return this.bb
}
}
}
这两个例子对我来说似乎都是一样的。总结的问题是——这些变量的隐私是通过那些方式实现的吗?
最佳答案
这些代码块不相等。见下文:
function test(a, b){
let aa = a
let bb = b
return {
getA: () => {
return aa
},
getB: () => {
return bb
}
}
}
let testResult = test(1, 2);
console.log(testResult.aa)
//error
console.log(aa);
对比
function test(a, b){
//this here === window
this.aa = a
this.bb = b
return {
getA: () => {
return this.aa
},
getB: () => {
return this.bb
}
}
}
let testResult = test(1,2);
console.log(testResult.aa);
//can get aa
console.log(aa);
this
是 window
对象。所以aa
不是私有(private)的。与第一个 block 一样,它是 block 作用域的并且不可访问。所以 aa
在第一个中只是“私有(private)”的。
Is this the "right" way?
正如我mentioned这只是一个design pattern (revealing module pattern) 。警惕“正确”的方式。 “正确”是主观的,取决于上下文。没有“正确”的方法,但这是构建此类事物的常见方法。
这只是使用 closure确定变量的范围。 js 中没有“私有(private)”声明。只是作用域变量。
关于javascript - 这是将变量设置为私有(private)的正确方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53556637/