class - Same variablename and propertyname in a constructor in JavaScript -
consider following definition of class in javascript:
// car constructor function car(color) { var haswheels = true; this.color = color; this.haswheels = haswheels; } var redcar = new car('red'); console.log(redcar.haswheels);
it seems work because gives no errors in firefox , writes true
console. however, code correct or javascript forgiving? netbeans complains in car constructor variable haswheels
unused. not give hint haswheels
when type redcar.
. works property color
. have rename variable haswheels
e.g. _haswheels
? (i know in simple example set property hasweels
directly true
, not point of question.) new code like:
// car constructor function car(color) { var _haswheels = true; this.color = color; this.haswheels = _haswheels; } var redcar = new car('red'); console.log(redcar.haswheels);
this seems work fine netbeans. however, rather gives properties , variables same name, since @ end assigned. this['haswheels'] = haswheels
in last line of constructor seems not work.
for worth works fine in netbeans:
function car(color) { var haswheels = true; return { color: color, haswheels: haswheels }; } var redcar = new car('red'); console.log(redcar.haswheels);
yes, can have same name. function argument in same namespace function's local variables, properties of object different.
you can think of arguments , local variables items on local scope object (or scope chain) whereas properties of current object properties of object pointed this
. 2 namespaces different. 1 reached no qualifier in color
. other reached referencing object in this.color
. so, this.color = color
works fine - assigning variable's value 1 namespace property in object's namespace - 2 separate variables.
in example doesn't work:
// car constructor function car(color) { var haswheels = true; this.color = color; this.haswheels = haswheels; }
there should no issue there either , seems work fine here: http://jsfiddle.net/jfriend00/7psg9/
Comments
Post a Comment