0

below is the first_code.

function Person(name){
    this.name = name;  
};
var p1 = new Person('go');
Person.prototype.getname = function(){
    return this.name
}

p1.getname(); // go ( p1 inherits the getname property ) 

however, here comes the second_code,

function Person(name){
    this.name = name;  
}
var p1 = new Person('go');
Person.prototype.getname = function(){
    return this.name
}

p1.getname(); // go ( p1 inherits the getname property ) 

function Person2(){};
var p2 = new Person2();
Person2.prototype = p1;

p2.getname(); // error (p2 does not inherit the getname property)

why p2.getname() does not work?

i`ve checked that if i switch the code like below, it works.

function Person2(){};
Person2.prototype = p1;
var p2 = new Person2();

p2.getname(); // go

but in the case of first_code, there were no problems regard to the sequences of code line,

but why is that wrong regards to the second_code?

need some help,

jwkoo
  • 2,393
  • 5
  • 22
  • 35

0 Answers0