This is javascript MDN example
The purpose is to illustrate the problem of let scope.
var SomeConstructor;{ let privateScope = {}; SomeConstructor = function SomeConstructor () { this.someProperty = "foo"; privateScope.hiddenProperty = "bar"; } SomeConstructor.prototype.showPublic = function () { console.log(this.someProperty); // foo } SomeConstructor.prototype.showPrivate = function () { console.log(privateScope.hiddenProperty); // bar }} var myInstance = new SomeConstructor(); myInstance.showPublic();myInstance.showPrivate(); console.log(privateScope.hiddenProperty); // error
But usually we don’t define a constructor like this.
So I rewrote it.
function SomeConstructor() { this.someProperty = 'foo'; let privateScope = {}; privateScope.hiddenProperty = 'bar'; SomeConstructor.prototype.showPublic = function () { console.log(this.someProperty); } SomeConstructor.prototype.showPrivate = function () { console.log(privateScope.hiddenProperty); }}var myInstance = new SomeConstructor(); myInstance.showPublic(); //foomyInstance.showPrivate(); //barconsole.log(privateScope.hiddenProperty); //ReferenceError: privateScope is not defined
You can see that we cannot directly access privateScope.hiddenProperty, if we change it like this.
var privateScope = {}; // 把let 换成var
The result becomes
console.log(privateScope.hiddenProperty); //ReferenceError: privateScope is not defined
You can see that the result remains unchanged.
In the constructor, whether it is var or let, its scope is the same, and they are all private variables.
We still use the example in MDN. If we change let to var
var SomeConstructor;{ var privateScope = {}; SomeConstructor = function SomeConstructor () { this.someProperty = "foo"; privateScope.hiddenProperty = "bar"; } SomeConstructor.prototype.showPublic = function () { console.log(this.someProperty); // foo } SomeConstructor.prototype.showPrivate = function () { console.log(privateScope.hiddenProperty); // bar }} var myInstance = new SomeConstructor(); myInstance.showPublic(); myInstance.showPrivate(); console.log(privateScope.hiddenProperty); // bar
, we can see that console.log has the result output instead of error.
But Under normal circumstances, we still use common patterns to define a constructor. This example is written specifically to explain the difference between let and var. So it's not representative.
Under the commonly used mode, there is no difference between let and var. They are both private variables of the constructor and have the same scope.
The above is the detailed content of Understanding of let and var examples in javascript MDN. For more information, please follow other related articles on the PHP Chinese website!