Reputation: 720
When trying executing the two following code blocks separately: The first one:
function Hallo() {
}
var some_obj = {
name: "Fred",
age: 23,
}
Hallo.prototype = some_obj;
var obj = new Hallo();
obj.constructor;
And the second one:
function Hallo() {
}
Hallo.prototype.name = 'Khanh';
Hallo.prototype.age = 23;
var obj = new Hallo();
obj.constructor;
I got the result in firebug's console is "Object{}" for the first and "Hallo()" for the second. While the second one is pretty simple to understand but the first one is really odd. Because as I know the constructor of the obj Object in the first one is still the same (that is Hallo() function). However I got Object() function in result. I really cann't understand why. Could you help me with it? Thank you!
Upvotes: 1
Views: 566
Reputation: 160973
The reason is:
When you do var obj = new Hallo();
, then
console.log(obj.constructor === Hallo.prototype.constructor); // true
In your first example, you assigned Hallo.prototype
with a new object, whose constructor
is function Object
(function Object(){...}
).
In your second example, the Hallo.prototype.constructor
is still function Hallo() {...}
Upvotes: 2
Reputation: 21
prototype will get a reference that point to the constructor by default, int the first function you overwrite the prototype to some_obj, the constructor reference changes at the same time to some_obj's constructor reference --Object's constructor Object()
Upvotes: 1