object Object being written

43 Views Asked by At

I am very new to JS and am playing around trying to output this verify function I came across below.

In my limited thinking I thought that the result would be false and I would be able to write that using document.write(), however it just writes [object Object] refer to https://jsfiddle.net/zyac0etj/

Hoping someone can explain/answer this for me..

function MyData(foo, bar) {
    this.foo = foo;
    this.bar = bar;

    this.verify = function () {
        return this.foo === this.bar;
    };
}

\\my addendum
var test = new MyData("myfoo","mybar");
document.write(test);
3

There are 3 best solutions below

0
connexo On

This is going on:

console.log(({}).toString());

document.write(str) expects a string. If you pass anything to it which is not a string, that anything's toString() method is implicitly invoked. Objects have a toString() method which does this:

Object.prototype.toString = function() { return '[object Object]'; };
1
Axiumin_ On

Right now, you're just writing the entire object to the DOM, which is why it shows as [object Object]. Assuming you want to get the result of the verify function written to the document, you would have to run the verify function in your last line.

The fixed code would look something like this:

function MyData(foo, bar) {
    this.foo = foo;
    this.bar = bar;

    this.verify = function () {
        return this.foo === this.bar;
    };
}

var test = new MyData("myfoo","mybar");

// To see the difference between test and test.verify()
console.log("Test object:", test);
console.log("Verify result:", test.verify());

document.write(test.verify());

You can also see the difference between the test and test.verify() in the console.

0
Or Shalmayev On

The document.write() method writes a string of text to a document stream. for more information on document.write