【发布时间】:2025-12-09 23:30:01
【问题描述】:
我正在尝试创建一个类似类的方式来访问具有公共和私有函数/变量的对象,但我有点困惑为什么这个简单的测试代码不起作用。
// Class type object with just one value.
function Play(arg) { // Constructor.
var test = arg;
// Private, as not declared with "this." Obviously more complex in the future.
private_settest = function( val ) {
test = val;
}
// Public.
this.settest = function( val ) {
private_settest(val);
}
this.gettest = function() {
return test;
}
}
var a = new Play(1);
var b = new Play(2);
a.settest(100);
console.log(a.gettest());
console.log(b.gettest());
我希望输出为 1 2,但实际输出为 1 100。
我认为这是一个关闭问题,有人愿意解释我缺少什么吗?
单步执行 this.settest() 时: test 的闭包值为 1(这是正确的)。
进入 private_settest() 时: test 的闭包值为 2,这是错误的,应该是 1。
退出 private_settest() 时,闭包值再次回到 1。我猜这是被弹出的闭包。
我们将不胜感激!
谢谢。
【问题讨论】:
-
private_settest = function( val ) { test = val; }应该是function private_settest( val ) { test = val; } -
对了,你不希望输出是 100 2 吗?
-
始终使用严格模式!
标签: javascript scope closures