全网最详细对小白最友好的原型继承

26 阅读1分钟
//原型继承
// 1.建立一个函数Parent
function Parent(name) {
  this.name = name
  this.children = ['a', 'b']
}
// 2.建立一个函数Child
function Child() {

}

// 3.然后把Parent new给 Child函数原型上,意思就是Child用原型继承Parent
Child.prototype = new Parent()

// 4.然后再创建一个child实列,测试一下该继承会不会跟Parent数据共享了
let child = new Child()

//5.然后给children添加一个 c测试
child.children.push("c")

//6.结果
console.log(child.children)// ['a', 'b',  'c']

//7.然后再创建一个child1实列,测试一下该继承会不会跟child数据共享了
let child1 = new Child()
// 7.1在测试一下会不会无法向Parent传参
child1.name = 'CC'
//8.结果
console.log(child1)
// name: "CC"
// [[Prototype]]: Parent
// children: (4)['a', 'b', 'c']
// name: undefined


/*总结
原型链继承的主要问题:
1. 引用类型的属性被所有实例共享
2. 在创建Child的实例的时候,不能向Parent传参
*/