1

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!

3
  • You're overwriting the entire prototype in the first example, but in the second you're only adding two new properties. Commented Oct 17, 2012 at 2:52
  • Yes, I know it, but the constructor is still the same, isn't it? I concern about constructor. Commented Oct 17, 2012 at 3:00
  • 1
    constructor is overwritten by the constructor of your object when you overwrite the entire prototype. Commented Oct 17, 2012 at 3:04

2 Answers 2

2

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() {...}

Sign up to request clarification or add additional context in comments.

1 Comment

Thank xdazz, I did test you answer using firebug. and yes, it return exactly as you said. So if I do: var obj = new Hallo(), the constructor of obj is NOT really Hallo() function but always the Hallo.prototype constructor function. However, I read a book call Object Oriented Javascript, and it said: If I do: var obj = new Hallo(), then the obj Object is created by Hallo() constructor function. So it differ from you answer. Could you explain me about this confusion?
1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.