继承的理解
什么是继承 ?
继承:从别人哪里,继承东西过来(财产,房产)
代码层面相当于:继承一些属性和方法
继承的作用:可以让多个构造函数之间建立关联,便于管理和复用
比如:
人类属性:name,age
学生属性:name,age,className
工人属性:name,age,companyName
无论学生,还是工人,都是人类,所以人类原型上有的方法,他们都应该有
实现方案:将学生构造函数自己的原型对象的地址断开,指向人类实例对象,从而继承人类的原型对象的属性和方法

方法通过:原型继承
属性通过:借调,父构造函数的.call()
// 1. 定义Person构造函数 function Person (name, age) { this.name = name this.age = age } Person.prototype.say = function () { console.log('人类会说话') } // 2. 定义Student构造函数 function Student (name, age, className) { Person.call(this, name, age) // 实现构造属性的继承 this.className = className } // 3. 原型继承: 利用原型链, 继承于父级构造函数, 继承原型上的方法 // 语法: 子构造函数.prototype = new 父构造函数() Student.prototype = new Person() Student.prototype.study = function() { console.log('学生在学习') } let stu = new Student('张三', 18, '80期') stu.say() console.log(stu) // 方法通过 原型继承 // 属性通过 父构造函数的.call(this, name, age)
// 1. 定义Person构造函数 function Person (name, age) { this.name = name this.age = age } Person.prototype.say = function () { console.log('人类会说话') } // 2. 定义Student构造函数 function Student (name, age, className) { Person.call(this, name, age) this.className = className } // 3. 原型继承: 利用原型链, 继承于父级构造函数, 继承原型上的方法 // 语法: 子构造函数.prototype = new 父构造函数() // 构造函数没有必要执行,我们只需要的是原型链 Student.prototype = Object.create(Person.prototype) Student.prototype.study = function() { console.log('学生在学习') } let stu = new Student('张三', 18, '80期') stu.say() console.log(stu) // 总结: // Object.create() 以参数的对象, 作为新建对象的__proto__属性的值, 返回新建的对象


浙公网安备 33010602011771号