原型
<script>
/* 用混合的方式构造对象 */
/*
构造函数+prototype
构造函数:属性
原型prototype:方法
*/
function Person(name,age){
this.name=name;
this.age=age;
}
/* 函数重复,浪费资源,解决方法:原型 */
Person.prototype.eat=function(){
document.write(`<p>${this.name}年级${this.age}会吃饭</p>`);
}
Person.prototype.color='yellow'
let a=new Person('qq',18)
let b=new Person('qq',19)
let c=new Person('qq',20)
document.write(a.color);
a.eat()
b.eat()
c.eat()
原型继承实例化对象
function Person(){
this.head=1;
this.foot=2;
}
function Student(name,no){
this.name=name;
this.no=no
}
/* 让学生类继承人类的属性 */
Student.prototype= new Person()
/* 加上constructor属性,并将这个属性指回原来的构造函数 */
Student.prototype.constructor=Student;
let stu1=new Student()
console.log(stu1);
/* console.log(stu1.head);
console.log(stu1.foot); */
原型继承直接继承
function Person(){
/* this.head=1;
this.foot=2; */
}
Person.prototype.head=1;
Person.prototype.foot=2;
/* 不变的属性都可以直接写入Person.prototype */
function Student(){
}
/* Student想要继承Person的属性 */
/* 直接继承prototype */
Student.prototype=Person.prototype
let s1=new Student();
/* console.log(s1); */
/* 缺点 */
/*任何对Student.prototype的修改,都会反映到Person.prototype */
/* Student的constructor不会指向自己 */
Student.prototype.name='zhangsan';
console.log(s1);
/* Student想要继承Person的属性和方法 */
利用空对象作为中介继承
/* 空对象,几乎不占内存
修改Student的prototype对象,不会影响到Person的prototype对象
*/
function Person(){}
Person.prototype.head=1;
Person.prototype.foot=2;
/* 子类想继承父类的属性 */
function Student(){}
/* 新建一个空对象 */
function f(){}
/* 把父类的原型直接赋值给空对象的原型上 */
f.prototype=Person.prototype
/* 把空对象的实例化对象 给到子类的原型上 */
Student.prototype=new f()
/* ☆constructor构造器都是指向自己的 */
Student.prototype.constructor=Student;
let stu1=new Student();
console.log(stu1);
/* 不会影响到Person的prototype对象 */
/* let stu1=new Student();
Student.prototype.age=30;
let p=new Person();
console.log(p); */
/* 原型链就是一层一层向上找的过程 */
/* 原型链继承就是利用了上面这种特性 */
/* 空对象,几乎不占内存
修改Student的prototype对象,不会影响到Person的prototype对象
*/
function Person(){}
Person.prototype.head=1;
Person.prototype.foot=2;
/* 子类想继承父类的属性 */
function Student(){}
/* 新建一个空对象 */
function f(){}
/* 把父类的原型直接赋值给空对象的原型上 */
f.prototype=Person.prototype
/* 把空对象的实例化对象 给到子类的原型上 */
Student.prototype=new f()
/* ☆constructor构造器都是指向自己的 */
Student.prototype.constructor=Student;
let stu1=new Student();
console.log(stu1);
/* 不会影响到Person的prototype对象 */
/* let stu1=new Student();
Student.prototype.age=30;
let p=new Person();
console.log(p); */
/* 原型链就是一层一层向上找的过程 */
/* 原型链继承就是利用了上面这种特性 */