Discuss
/
JavaScript
/
换一种方法
换一种方法
Topic source来自初学者的理解。 你代码中的
Student.prototype.constructor.prototype=Person.prototype
相当于
Student.prototype=Person.prototype
因为
Object.prototype.constructor===Object//true
导致Student和Person共享了原型对象
var lucy = new Person('lucy',13);
lucy instanceof Student;//true应该为false
如果为Student的原型对象增加一个方法
Student.prototype.intro=function(){return "I am a Student";}
lucy.intro()//"I am a Student"
解决办法为改成
function Person(name,age){
this.name = name;
this.age = age;
}
function Student(name,age,className){
Person.call(this,name,age);
this.className = className;
}
Student.prototype = Object.create(Person.prototype);//修改后
var p = new Person('lucy',22);
var s = new Student('tom',12,'grade1');
p instanceof Student;//false
s instanceof Person;//true
Student.prototype.intro=function(){return 'I am a student'};
p.intro()//报错
s.intro()//"I am a student"
- 1
lmtooT_T
这么搞好像也可以