Why we can update value of (public) members (method or properties) of a javascript object, and even after its execution (member should be out of scope as in traditional language)?
Asked
Active
Viewed 63 times
-3
-
Can you give an example? The terminology is a bit unclear otherwise. – Thilo Nov 17 '14 at 06:58
-
1"members of a method"? – Amadan Nov 17 '14 at 06:58
-
Are you asking about [closures](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work)? – Paul Nov 17 '14 at 07:33
1 Answers
0
In JavaScript, properties can be dynamically added, removed, or altered.
var obj = {
member: function() {
alert('Hi');
}
};
obj.member(); // alerts 'Hi'
alert(obj.member); // alerts the definition of the anonymous function
obj.member = 42;
alert(obj.member); // now since the property is replaced, this alerts 42
The possibility of easily adding or removing properties is by design in JavaScript. This is because JavaScritp is a dynamic language, unlike static languages such as Java or C#.
Now let's look at what happens when we replace functions who use closures:
function MyObj() {
var secret = 0;
this.changeSecret = function() {
secret++;
alert('Secret is: ' + secret);
}
}
var obj = new MyObj();
obj.changeSecret(); // alerts 'Secret is: 1'
// we are saving a reference for the (anomymous) function contained in 'changeSecret'
var changer = obj.changeSecret;
// and then replacing the changeSecret property with another function
obj.changeSecret = function() {
alert('I do not know the secret');
};
obj.changeSecret(); // alerts 'I do not know the secret'
changer(); // alerts 'Secret is: 2' the function still has access to variables
// inside MyObj
The second example works because JavaScript closures. See How do JavaScript closures work?

Community
- 1
- 1

sampathsris
- 21,564
- 12
- 71
- 98