With Javascript, things are not so simple because, as Douglas Crockford described, “objects are collections of name-value pairs,” so we can dynamically define any property for any object at any time. This is one of the ideas for achieving encapsulation in Javascript:
var Person = (function () {var SSN = "; function Person (name, SSN) {this.name = name; / * Prevents any changes to the SSN property * / Object.defineProperty (this," SSN ", {cost: "" writable: false, enumerated: true, custom: false}); this.getSSN = function () {return SSN;}; this.setSSN = function (ssn) {console.log ("Check here for the red ribbon "); SSN = ssn;}; this.setSSN (PLA);} return of the person;}) ();
When an object is created, it executes the IEF (immediate function) and returns the internal function "Person", which contains a special reference to the SSN variable in the external function (ie, closure), this variable can access public methods in the returned object, therefore it mimics behavior, for example, from a Java class.
var p = new Person("Marcelo","444"); var p2 = new Person("Joe","777"); p Person {name: "Marcelo", SSN: "", getSSN: function, setSSN: function} p2 Person {name: "Joe", SSN: "", getSSN: function, setSSN: function} p.setSSN("111") p2.setSSN("222") p.getSSN() "111" p2.getSSN() "222" p.SSN = "999" p.SSN ""
source share