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 ???
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.
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