0

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 Answers3

0

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]'; };
connexo
  • 53,704
  • 14
  • 91
  • 128
0

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.

Axiumin_
  • 2,107
  • 2
  • 15
  • 24
  • Thank you for the thorough explanation! I see the error in my thinking now. It should've been document.write(test.verify()); – Mike Devine Jul 28 '22 at 00:01
0

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

Or Shalmayev
  • 295
  • 1
  • 12