Is this situation acceptable?
No, there is an error on the final line. The c
object does not contain an a
property:
a = function (name){this.name = name};
a['b'] = function (age){this.age = age};
c = new a('John');
c.a['b'](30); // This line throws a TypeError
new a
generates an object that inherits from the object indicated by a.prototype
. However, a.prototype
does not have an a
property.
If you wish to access a
from c
, you can utilize the constructor
property in a.prototype
which points to a
:
c.constructor['b'](30);
However, executing this would make the second function consider this
as pertaining to c.constructor
and consequently add an age
property to the initial function:
a = function (name){this.name = name};
a['b'] = function (age){this.age = age};
c = new a('John');
c.constructor['b'](30);
console.log(a.age); // Outputs: 30
In retrospect, the overall structure of
a = function (name){this.name = name};
a['b'] = function (age){this.age = age};
c = new a('John');
...seems somewhat illogical. It's typically unnecessary to place b
under a
in such a manner.
Additional note: Your code is susceptible to The Horror of Implicit Globals (an article on my personal blog): Remember to declare your variables.