原型链实例化继承
/* 构造函数可以理解为一个类 */
function Person() {
this.head = 1;
this.foor = 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);
function Car() {
this.color = '黑色';
this.price = '100w';
}
function Bmw() {
}
Bmw.prototype = new Car();
Bmw.prototype.constructor = Bmw;
let bmw1 = new Bmw();
console.log(bmw1.color);
console.log(bmw1.price);
复制代码
原型链直接继承
function Person() { }
/* 不变的属性都可以直接写入Person.prototype */
Person.prototype.head = 1;
Person.prototype.foot = 2;
function Student() {}
Student.prototype = Person.prototype;
let stu1 = new Student();
console.log(stu1.head);
/* 缺点
任何对Student.prototype 的修改,都会反映到Person.prototype
*/
复制代码
利用空对象作为中介继承
/* 空对象 ,几乎不占内存
修改子不影响父
*/
function Person() { }
Person.prototype.head = 1;
Person.prototype.foot = 2;
/* 子类想继承父类的属性 */
function Student() { }
/* 新建一个空对象 */
function f() { }
/* 把父类的原型直接复制给空对象的原型上 */
f.prototype = Person.prototype;
/* 把空对象的实例化对象给 Student 原型上 */
Student.prototype = new f();
Student.prototype.constructor = Student
let stu1 = new Student();
console.log(stu1.foot);