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?
propertyobject? I'd think you should create the variables you want in the object declaration, and then usePerson.prototype.sayName = function(){}afterwards. I'm thinking that theprototypealso contains various other Object-related things that you're removing by overwritting it completely in your second example.