首先要知道:
new 一个对象的过程:
1.创建了一个对象
2.将this指向这个对象
3.执行构造函数
4.返回这个对象
当访问一个对象的一个属性时:在这个对象本身上找,找到就返回,找不到就去这个对象的__proto__属性指向的那个对象上找(也就是prototype对象)
function Person(){
}
Person.prototype.name="xingming";
Person.prototype.age=20;
Person.prototype.sayhello=function(){
console.log(this.name)
}
var p=new Person();
p.sayhello();//xingming
//现在想让Student继承Person
//一、原型链继承
function Student(){}
Student.prototype=Person.prototype;//这样写不行!!!会修改Person的原型
Student.prototype=Object.create(Person.prototype)
//二、组合继承(构造函数加原型链继承)
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.sayhello=function(){
console.log(this.name)
}
function Student(name,age,classid){
Person.call(this,name,age);//构造函数继承
this.class=classid;
}
Student.prototype=Object.create(Person.prototype);//原型链继承
Student.prototype.study=function(){
console.log(this.name,this.age,this.classid)
}
var student=new Student('哪吒','2','3班')