如何实现 在子类中通过 call或者apply来调用父类的构造函数
重点:用.call()和.apply()将父类构造函数引入子类函数(在子类函数中做了父类函数的自执行(复制))
特点:1、只继承了父类构造函数的属性,没有继承父类原型的属性。
2、解决了原型链继承缺点1、2、3。
3、可以继承多个构造函数属性(call多个)。
4、在子实例中可向父实例传参。
缺点:1、只能继承父类构造函数的属性。
2、无法实现构造函数的复用。(每次用每次都要重新调用)
3、每个新实例都有父类构造函数的副本,臃肿。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
</html>
<script type="text/javascript">
//实现 在子类中通过 call或者apply来调用父类的构造函数
function Person(name, age) {
this.name = name;
this.age = age;
this.say = function() {
console.log("hi")
}
}
//通过person的原型定义一个address
Person.prototype.address = "北京"
function Student(classname, name, age) {
this.classname = classname;
//在子类中调用父类的构造函数
//Person.call(this,name,age)
Person.apply(this, [name, age]);
}
var stu = new Student('2003A', "小四", 20)
var stu1 = new Student('2003A', "下午", 21)
console.log(stu.address)
console.log(stu1)
</script>