ForbetterCoder
ForbetterCoder

Reputation: 89

I can't explain the result of the following output

I am trying to read source code of jQuery but some basic concept stops me. To make it simple, I write the following code, but the output turn out to be weird.

function Foo(){
}
var foo = new Foo();
var foo2 = new Foo();

console.log(Foo.toString == Foo.prototype.toString); // false
console.log(foo.toString === Foo.toString); // false
console.log(foo.toString == foo2.toString); // true

I can't tell why the first and the second are false. I've learned that any custom object must inherit Object, and I didn't override toString method at all, but why foo.toString !== Foo.toString !== Foo.prototype.toString ???

Upvotes: 3

Views: 80

Answers (2)

Felix Kling
Felix Kling

Reputation: 816442

The first two are false because you are comparing a method of a function against a method of an object.
That would not be a problem by itself, but functions override toString. So essentially, you are comparing Function.prototype.toString and Object.prototype.toString, which are different functions.

console.log(Foo.toString == Foo.prototype.toString);

Is the same as Function.prototype.toString == Object.prototype.toString, since Foo is a function and inherits from Function.prototype, but Foo.prototype is an object, inheriting from Object.prototype.

console.log(foo.toString === Foo.toString);

Same here. foo is an object, inheriting from Foo.prototype, which is an object.


These output true:

console.log(Foo.toString == Function.prototype.toString); // true
console.log(foo.toString === Object.prototype.toString); // true
console.log(foo.toString === Foo.prototype.toString); // true

The last one is true because the foo is created through the constructor function Foo and therefore inherits from Foo's prototype, Foo.prototype.

Upvotes: 1

Florian Margaine
Florian Margaine

Reputation: 60747

You're not comparing the output of the methods, you're comparing the references. In javascript, the equal operators compare the references, except for primitive values (to keep it simple).

Example in code:

var foo = 5, bar = 5;
foo === bar // true

var foo = function() {}, bar = function() {};
foo === bar // false

// If you were to compare the outputs, the following would be true:
foo() === bar() // true

To come back to your example:

  • Foo.toString is not the same reference as Foo.prototype.toString, but it is the same reference as Function.prototype.toString.
  • foo.toString is not the same reference as Foo.toString. It is the same as Foo.prototype.toString (check foo.toString === Foo.prototype.toString, it is true).
  • foo and foo2 are two different objects. This is why their methods are not the same reference.

Some examples to illustrate:

Foo.toString === Function.prototype.toString // true
foo.toString === Foo.prototype.toString

Upvotes: 0

Related Questions