| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <script>
- /**
- * 组合继承:原型链 + 构造函数
- * 实现:call/apply + 原型链
- * 优点:
- * 解决原型链继承父类无法传参
- * 解决了原型链中父类共享实例
- * 解决了构造函数继承无法继承父类原型上的方法
- * 缺点:父类的构造函数被调用了两次 代码冗余
- */
- function Person(name1) {
- this.name = name1;
- this.age = 3;
- this.list = ["吃饭", "睡觉", "打豆豆"];
- }
- Person.prototype.say = function () {
- console.log("hello");
- }
- function Child(name1) {
- // 1.构造函数继承
- Person.apply(this,[name1]);
- };
- // 2.原型链继承
- Child.prototype = new Person();
- // 修改构造函数的指向
- Child.prototype.constructor = Child;
- Child.prototype.say1 = function() {
- console.log("hi");
- }
- let c1 = new Child('图图');
- let c2 = new Child('喜羊羊');
- c1.list.push("玩耍");
- console.log(c1, 'c1')
- console.log(c2, 'c2')
- c1.say();
- c1.say1();
- </script>
- </body>
- </html>
|