javascript - If a variable is enclosed, and an instance sets a property with the same name, where does the property go? -
most of know javascript has no sense of "private" properties, behavior can emulated through use of closures:
var car = function () { var name = 'tesla'; var wheelcount = 4; this.getname = function () { return name; }; this.getwheelcount = function () { return wheelcount; }; this.setname = function (newname) { name = newname; }; this.setwheelcount = function (newcount) { wheelcount = newcount; }; }; var mycar = new car(); console.log(mycar.name); // undefined
that makes sense know how javascript closures work. however, following work:
mycar.name = 'corvette'; console.log(mycar.name); // 'corvette'
but if call function prototype, enclosed variable still used
console.log(mycar.getname()); // 'tesla'
when call mycar.name
, you're adding new property object. entire point of using this
when declaring getname
(etc) functions inside car
definition make differentiation between enclosed name
inside car
declaration versus mycar.name
?
i have feeling know answer this, certain. plus, think invaluable other people getting advanced grasp on how javascript enclosures work.
is entire point of using
this
when declaringgetname
(etc) functions insidecar
definition make differentiation between enclosed name insidecar
declaration versusmycar.name
?
yes.
this
(or mycar
) object, on put properties want have (in case methods). if want use properties, must use property accessor.
var name
local variable in constructor function, accessed closure object's methods.
or, answer title question:
if variable enclosed, , instance sets property same name, property go?
the property goes on object. doesn't interfere @ variable, located in scope of car
constructor invocation.
Comments
Post a Comment