1

I'm reading professional javascript for web developers, and they present the following:

This code works:

var friend = new Person();

Person.prototype.sayHi = function(){
    alert("hi");
};

friend.sayHi();

but this code does not:

function Person(){
}

var friend = new Person();

Person.prototype= {
   constructor: Person,
   name: "Nicholas",
   age: 29,
   job: "Software Engineer",
   sayName: function () {
       alert(this.name);
   }
};

friend.sayName();

I get that, in the second example, the prototype is defined after the friend variable is instantiated, but in that case, why does the first example work?

2
  • 1
    I'm no expert at this - but are you allowed to completely overwrite the property object? I'd think you should create the variables you want in the object declaration, and then use Person.prototype.sayName = function(){} afterwards. I'm thinking that the prototype also contains various other Object-related things that you're removing by overwritting it completely in your second example. Commented Mar 10, 2013 at 22:33
  • 1
    In first sample you're adding a property to a prototype, in the second - overriding the whole prototype. The cases just not comparable. Change them to look alike and you'll get the same behaviour Commented Mar 10, 2013 at 22:33

1 Answer 1

4

In the first snippet, you are adding to the existing prototype that has already been provided to the instance. In the second, you are creating a new prototype for Person, which is different from the prototype object that has already been given to friend.

If you are adding new functions to the prototype, you can do it at any time before that function gets called. Assigning a new object to the constructor function's prototype needs to be done before instantiating new instances.

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

2 Comments

additional question: if the prototype had not yet been defined in the first example, would it no longer work?
A default prototype gets constructed when you declare the function.

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.