If you want to not complicate the situation (and completely abandon what you have done so far), as @AlienWebguy suggests, you donโt even need the .io element, which, in the end, displays the same way as the .name properties and .age :
john.io.set('name', 'Johnny');
In the end, the .io object is as open as the .name and .age , so it is a complex solution that does not make any progress in encapsulating or hiding information. (sorry @AlienWebguy, this is how I feel)
If you are trying to use the classic inheritance paradigm and completely abandon the usual OOP JavaScript, then abandon the traditional paradigm of function-as-constructors and forget about using the this link in your constructors:
// first create a constructor var Person = function(arg0, arg1) { var that = {}; // private variables var age = arg0; var name = arg1; // public methods that.getName = function() { return name; }; that.getAge = function() { return age; }; that.setAge = function(a) { age = a; }; return that; }; var john = new Person('johnathan', 33); console.log(john.name); // undefined console.log(john.getName()); // 'johnathan' console.log(john.age); // undefined console.log(john.getAge()); // 33 john.setAge(28); console.log(john.getAge()); // 28 john.setName("Richard"); // Error - setName is not a function
This is an example of Douglas Crockford Parasitic inheritance ... but without part of the "inheritance". The fact is that the instance variables age and name are private, but remain in the visible range due to the visibility of the JavaScript functional variable, so object methods can still control them.
You will also notice that the name variable does not have a setter, so this method will legally allow you to control access to the name variable - there are no hidden this.name and this.io that will allow the variable to be manipulated; it is completely closed.
source share