这是一个javascript关闭?

dub*_*ech 1 javascript closures function

我有这个....

function MyFunction() {
    var myVar = "I think I am encapsulated";

    this.getMyVar = function() {
        return myVar;
    }
}

var myProperty = new MyFunction();
console.log(myProperty.getMyVar());

myProperty.myVar = "you're not encapsulated";
console.log(myProperty.getMyVar());
Run Code Online (Sandbox Code Playgroud)

它输出:"我想我被封装了两次".为什么?我不认为这是封闭......

Poi*_*nty 6

闭包围绕"getMyVar"函数.变量"myVar的" 内部构造是一个局部变量,而不是在函数外可见,除了从"getMyVar"的返回值.

在对象上设置"myVar"属性就是这样,但"getMyVar"函数不返回对象的属性; 它在闭包中返回局部变量的值.