-3

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)?

Sandeep Kumar
  • 1,505
  • 1
  • 15
  • 24

1 Answers1

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