一、面向对象的三大特性
- 封装
- 继承
- 多态
二、封装
当多个实例对拥有相同的属性和行为(方法)时,把这些相同的属性和行为抽象出来,减少不必要的代码。
三、继承
概念:A对象通过继承 B 对象,就能直接拥有 B 对象的所有属性和方法。
1、call继承
//人-构造函数
function Person(name, age) {
this.type = 'human'
this.name = name
this.age = age
this.say = function () {
console.log("说话>>");
}
}
Person.prototype.eat = function(){
console.log('吃东西');
}
//学生-构造函数
function Student(name, age) {
Person.call(this,name,age); // 借用构造函数继承成员
}
var s1 = new Student('张三', 18)
console.log(s1.type, s1.name, s1.age) // => human 张三 18
console.log(s1.say());
s1.eat();
Person.call(this,name,age);
Student这个对象继承Person对象
call 方法可以用来代替另一个对象调用一个方法,将一个函数的对象改变为由 this 指定的新对象。
不能继承父对象的原型对象
2、拷贝继承
//人-构造函数
function Person(name, age) {
this.type = 'human'
this.name = name
this.age = age
this.say = function () {
console.log("说话>>");
}
}
Person.prototype = {
constructor: Person,
eat: function () {
console.log('吃东西');
}
}
//学生-构造函数
function Student(name, age) {
Person.call(this, name, age); // 借用构造函数继承成员
}
// 原型对象拷贝继承原型对象成员
for (const key in Person.prototype) {
Student.prototype[key] = Person.prototype[key];
}
// console.dir(Person)
// console.dir(Student)
var s1 = new Student('张三', 18)
console.log(s1.type, s1.name, s1.age) // => human 张三 18
console.log(s1.say());
s1.eat();
通过遍历父对象的原型对象到达继承父对象的所有方法和属性,及原型对象
for (const key in Person.prototype) {
Student.prototype[key] = Person.prototype[key];
}
三、原型继承
//人-构造函数
function Person(name, age) {
this.type = 'human',
this.name = name,
this.age = age
}
Person.prototype.sayName= function(){}
function Student(name,age){}
//利用原型对象的特性实现继承
Student.prototype = new Person();
console.dir(Person)
console.dir(Student)
prototype属性:每个函数都一个prototype属性,这个属性指向函数的原型对象。原型对象主要用于共享实例中所包含的的属性和方法。
![](https://img.haomeiwen.com/i20074990/5ea7079995959f4a.png)
网友评论