In this code:
function Cls() {
this._id = 0;
Object.defineProperty(this, 'id', {
get: function() {
return this._id;
},
set: function(id) {
this._id = id;
},
enumerable: true
});
};
var obj = new Cls();
obj.id = 123;
console.log(obj);
console.log(obj.id);
I would like to get { _id: 123, id: 123 } but instead I get { _id: 123, id: [Getter/Setter] }
Is there a way to have the getter value be used by the console.log function?
Steps to Open the Console Log in Google Chrome By default, the Inspect will open the "Elements" tab in the Developer Tools. Click on the "Console" tab which is to the right of "Elements". Now you can see the Console and any output that has been written to the Console log.
Getters (a.k.a. Accessors) simply return the title , author , and rating instance variables, respectively. Note that the name of the first getter is getTitle . Prefixing the corresponding instance variable with "get" is a common naming convention for getters. Getter methods shine in complex classes.
Well, for those interested, getters and setters are a method of allowing accessibility of private variables inside a function. This ensures a user cannot get or set the variable unless they use the defined getter/setter methods.
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
You can use console.log(Object.assign({}, obj));
Use console.log(JSON.stringify(obj));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With