I was I running the following code,
function Person(){}
var person1 = new Person();
Person.prototype= {
name : "Ann",
sayName : function(){
console.log( this.name);
}
}
person1.sayName();
it will show an error "Object # has no method 'sayName'". This cause en error because the prototype that person1 points to doesn't contain a property of that name. My question is when I change the way I define the prototype as the following:
function Person(){}
var person1 = new Person();
Person.prototype.name = "Ann";
Person.prototype.sayName = function(){
console.log(this.name);
}
person1.sayName();
It runs correctly with "Ann". Can anyone tell me why this happens? Thank you.