Using Object.DefineProperty and accessing a variable in a private area

The following does not work from my recipient: I do not see the _nickname defined in the Person class.

 var Person = function (args) { var _nickname = ''; if (args === undefined || args === null) { return; } if (args.nickname !== undefined && args.nickname !== null) { _nickname = args.nickname; } } Object.defineProperty(Person.prototype, "nickname", { get : function () { return _nickname; } }); var x = new Person({ nickname : 'bob' }); console.log(x.nickname); 

How to do it? Is there a way to add _nickname to the Person prototype from its function?

+4
source share
1 answer

Is there a way to add _nickname to the Person prototype from its function?

If you mean the constructor of Person , I am sure (although, in my opinion, it does not look very elegant):

 var Person = function (args) { var _nickname = ''; if (args === undefined || args === null) { return; } if (args.nickname !== undefined && args.nickname !== null) { _nickname = args.nickname; } Object.defineProperty(this, "nickname", { get : function () { return _nickname; } }); } var x = new Person({ nickname : 'bob' }); console.log(x.nickname); 

http://jsfiddle.net/JEbds/

In this case, your getter is just another closure, so it has access to _nickname . And this is not on the prototype anymore, you need your own property to accomplish this.

+5
source

Source: https://habr.com/ru/post/1498279/


All Articles