How does function scope work in JavaScript? -
i having trouble understanding function scope in javascript:
function person() { var _firstname; var _lastname; } personone = new person(); personone._firstname = "fred"; alert(personone._firstname);
this outputs "fred", thought variables of person function accessible inside function. why work?
in javascript, objects dynamically-expandable.
for example:
var obj = {}; obj.firstname = "matÃas"; // <-- adds property if doesn't exist
in other hand, if want declare properties should part of object in constructor function need qualify them this
:
function person() { this._firstname = null; this._lastname = null; }
extra info
if want avoid objects being dynamically-expandable, can use ecma-script 5 object.preventextensions
function:
var obj = {}; object.preventextensions(obj); // property won't added! obj.text = "hello world";
Comments
Post a Comment