Reputation: 523
Code as follows:
function Teacher(name, age) {
this.name = name;
this.age = age;
}
Teacher.prototype.sayName = function() {
alert(this.name);
};
Teacher.prototype.sayHi = function() {
alert("Hi, I'm " + this.name);
};
console.log(Teacher.prototype instanceof Teacher); // false
console.log(Teacher.prototype instanceof Object); // true
console.log(Teacher.prototype); // Teacher {sayName: function, sayHi: function}
p.s. The output above is in chrome. The first console.log shows that Teacher.prototype is not an instance of Teacher, but the third one shows that Teacher.prototype is an instance of Teacher(intuitively), which is contradictory.
I know that the second console.log is true since Object.prototype is in the prototype chain of Teacher.prototype, exactly Teacher.prototype.__proto__ === Object.prototype
. Thus the first console.log should output false.
But I am confused why output of third console.log shows Teacher.prototype is an instance of Teacher. Can anyone clarify that for me? Thanks a lot.
Upvotes: 1
Views: 117
Reputation: 816780
That's just how the Chrome console chooses to display objects. It looks at the constructor
property of the object and then assumes it is an instance of that constructor function.
This works fine for all objects, except prototype objects, because their constructor
property refers to the function they are the prototype of and not the constructor function they are created from.
Examples:
console.log(Teacher.prototype.constructor === Teacher); // logs true
// Lets overwrite the constructor
function Foo() {};
Teacher.prototype.constructor = Foo;
console.log(Teacher.prototype);
// logs Foo {sayName: function, sayHi: function}
Upvotes: 1
Reputation: 72279
But I am confused why output of third console.log shows Teacher.prototype is an instance of Teacher. Can anyone clarify that for me? Thanks a lot.
Your thinking is OK that Teacher.prototype
is not an instance of Teacher
. Let me make an educated guess where the Teacher comes from in the DevTools view:
var obj = new Teacher();
obj.constructor; // function Teacher
obj.constructor.name; // "Teacher"
var proto = Teacher.prototype;
proto.constructor; // function Teacher
proto.constructor.name; // "Teacher"
Looks like Chrome DevTools console checks .constructor.name
when pretty-printing objects, which is reasonable. Prototype objects (which are created together with functions and accessible via .prototype
) also have a .constructor
property that follows back to the function.
Upvotes: 3