关于JS的面向对象的思考和总结

面向对象编程的概念和原理

1、面向对象编程是什么
它是用抽象的方式创建基于现实世界模型的编程模式(将数据和程序指令组合到对象中)
2、面向对象编程的目的
在编程中促进更好的灵活性和可维护性,在大型软件工程中广为流行。
3、面向对象编程的优势(继承、多态、封装)
继承:获取父类的全部(数据和功能),实现的是复制。
多态:根据实现方法的对象,相同方法名具有不同的行为。
封装:聚合对象数据和功能,以及限制它们和外界的联系(访问权限)。

JS中如何实现面向对象编程(参考

1、原型链式继承
function Person() {
    this.name = 'per'
    this.obj = {
        name: ''
    }
}
Person.prototype.getName = function() {
    return this.obj.name
}
Person.prototype.setName = function(name) {
    this.name = name
    // 引用类型的赋值会同步给所有子类
    this.obj.name = name
}
function Student() {
    
}
Student.prototype = new Person()

const stu1 = new Student()
const stu2 = new Student()

stu1.setName('stu')
stu1.getName()
stu2.getName()
缺点: 引用类型被修改时会同步给所有子类
2、构造函数继承
function Person() {
    this.obj = {
        name: 'a'
    }
    this.setName = name => {
        this.obj.name = name
    }
    this.getName = () => {
        return this.obj.name
    }
}
function Student() {
    Person.call(this)
}
const stu1 = new Student()
const stu2 = new Student()
stu1.setName('stu')
stu1.getName()
stu2.getName()
缺点:父类的函数在子类下面是不共享的,相当于动态的复制了一份代码
3、组合继承
function Person() {
    this.obj = {
        name: 'a'
    }
}
Person.prototype.getName = function() {
    return this.obj.name
}
Person.prototype.setName = function(name) {
    this.name = name
    // 引用类型的赋值会同步给所有子类
    this.obj.name = name
}
function Student() {
    // 继承属性
    Person.call(this)
}
// 继承方法
Student.prototype = new Person()
缺点:父类内的属性复制执行了两遍
4、寄生组合式继承
function Person() {
    this.obj = {
        name: 'a'
    }
}
Person.prototype.getName = function() {
    return this.obj.name
}
Person.prototype.setName = function(name) {
    this.name = name
    // 引用类型的赋值会同步给所有子类
    this.obj.name = name
}
function Student() {
    // 继承属性
    Person.call(this)
}
// 这里实现方法的继承
function inherit(sub, parent) {
    sub.prototype = Object.create(parent.prototype)
    sub.prototype.constructor = sub       
}
inherit(Student, Person)
这里解决了组合式继承的父类代码二次执行问题
5、class实现继承(参考
class Person {
    constructor(){
        this.obj = {
            name: 'a'
        }
    }
    get name() {
        return this.obj.name
    }
    set name(name) {
        this.obj.name = name
    }
}
class Student extends Person {
    constructor() {
        super()
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值