您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

JS如何实现面向对象编程?js面向对象编程的原理介绍

2025/2/18 6:35:41发布24次查看
本篇文章给大家带来的内容是关于js如何实现面向对象编程?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()    }}
相关推荐:
js面向对象 多种创建对象方法小结_js面向对象
javascript面向对象编程代码_js面向对象
以上就是js如何实现面向对象编程?js面向对象编程的原理介绍的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product