Im reading this article from Crockford: http://www.crockford.com/javascript/private.html
And in the section where he talks about Private, he says:
Private members are made by the constructor. Ordinary vars and parameters of the constructor becomes the private members.
Now if I do this in my script:
"use strict"
function car(brand) {
this.brand = brand;
var year = 2012;
var color = "Red";
}
var bmw = new car("BMW");
console.log(bmw.brand); // BMW -> VISIBLE ?!?
I can easily access property that was passed through constructor! Can someone explain this better, shouldn't these variables passed through constructor be private?
Thanks!
It's not that you can access values passed into the constructor. What you've done is set
this.brandequal to the value passed in the constructor. Therefore, the publicly availablebrandnow has the same value that was passed in. The localbrandinside the constructor!= this.branduntil you set it.