// 继续上一篇文章借用构造函数实现继承
// 为解决原型中包含引用类型值所带来的问题,
// 人们开始用一种叫做借用构造函数的技术来实现继承。
// 这种技术的基本思想非常简单,即在子类构造函数内部调用超类构造函数。
//1.首先创建一个Parent
function Parent(name) {
// 这里输出的this是Child
console.log(this)
this.name = name
this.children = ['a', 'b']
this.getName = function () {
return this.name
}
}
//2.然后创建一个Child
function Child(name) {
// call()方法使用一个指定的this值和单独给出的一个或多个参数来调用一个函数
Parent.call(this, name)
// Parent()
// this.name = name;
// this.children = ["a", "b"];
// this.getName = function () {
// return this.name;
// };
}
//3.这里 实例化同时传递一个参数C1
let child1 = new Child("C1");
//4.给child1添加一个c
child1.children.push("c");
// 5.然后输出看看是什么
console.log('child1', child1.name, "==", child1.children);
/*
这里的name成功被传递了C1
C1 == ['a', 'b', 'c']
*/
// 6.然后创建child2,顺便传递一个C2
let child2 = new Child("C2");
// 7.然后给children添加d
child2.children.push("d");
// 8.然后看看输出什么
console.log('child2', child2.name, "==", child2.children);
/*
c2也成功传入进去
C2 == ['a', 'b', 'd']
*/
// 最后再看看child1属性有没有被更改
console.log('child1', child1.name, "==", child1.children);
/*
拿到的是没有被更改的
C1 == ['a', 'b', 'c']
*/
// 接下来总结一下吧
// 优点: 避免了引用类型的属性被所有实例共享 可以直接在Child中向Parent传参
// 缺点: 方法都在构造函数中定义了,每次创建实例都会创建一遍方法
/* Child{}
>children: (3) ['a', 'b', 'd']
>getName: ƒ ()我说的方法就是这个也就是Parent每次都会被创建
name: "C2"
>[[Prototype]]: Object
*/