Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get console.log to output the getter result instead of the string "[Getter/Setter]"?

Tags:

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?

like image 427
Killroy Avatar asked Jan 21 '15 16:01

Killroy


People also ask

How do you check the output of a console log?

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.

Is a getter an accessor?

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.

Why do we need getter and setter methods in JavaScript?

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.

What is the getter function?

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.


2 Answers

You can use console.log(Object.assign({}, obj));

like image 148
quant2016 Avatar answered Sep 22 '22 23:09

quant2016


Use console.log(JSON.stringify(obj));

like image 26
jib Avatar answered Sep 26 '22 23:09

jib