// class 的多种继承方式
// 继承1 -- 原型链继承:子类的prototype为父类的实例
function Person() {
this.name = "person"
this.arr = [1, 2]//引用类型
}
Person.prototype.printName = function () {
console.log(this.name)
}
function Student() {
this.name="student"
}
Student.prototype = new Person() // -- Student.prototype = Person.prototype : 子类只能继承父类原型上的属性和方法 不能继承父类上的属性和方法
var stu = new Student()
stu.printName() // student
// 原型链继承的弊端: 1. 在父类构造函数中定义的引用类型数据时,继承子类一个实例改变该值后,所有继承子类实例该值都改变 (属性共享)
// 2. 在创建子类实例时,不能向构造函数传递参数
stu.arr.push(3)
console.log(stu.arr) // [1, 2, 3]
var stu2 = new Student()
console.log(stu2.arr) // [1, 2, 3]
function Stu() {
}
var s = new Stu()
Stu.prototype = new Person()
console.log(s.arr<
Class多种继承方式
最新推荐文章于 2022-04-20 23:34:00 发布