js封装技巧

150 阅读1分钟

在开发中,封装是一种重要的编程技巧。可以提高代码的可维护性、可复用性和安全性。以下是常用的封装技巧。

函数封装

讲一些功能实现封装为函数,可以复用,减少代码重复编写。

// 封装一个计算两数之和的函数
function add(a,b){
    return a+b
}

对象封装

在函数封装的基础上扩展,使用对象封装。对象里面包括数据和方法,可以实现数据和行为的绑定。

// 封装一个表示人的对象
const person = {
    name: 'john',
    age: '18',
    sayName(){
        console.log(`my name is ${this.name}`)
    }
}

// 使用封装对象
person.sayName()

构造函数封装

在对象封装的基础上,使用构造函数封装。可以重复构造对象,避免重复定义相同属性、方法的对象。

//封装构造函数
function Person(name,age){
    this.name=name
    this.age=age
    this.sayName(){
        console.log(`my name is ${this.name}`)
    }
}
//使用构造函数
const personOne=new Person('john',18)
const personTwo=new Person('lucy',20)

原型链封装

构造函数封装大大降低了重复编写代码,并且包括了前几个封装方法的优点,但是重复构造的对象方法功能一致,可以使用原型链封装降低内存。

function Person(name,age){
    this.name=name
    this.age=age
}

Person.prototype.sayName=function(){
    console.log(`my name is ${this.name}`)
}

const personOne=new Person('john',18)
const personTwo=new Person('lucy',20)

闭包封装

使用闭包封装,可以保护数据的安全私有性,不被外部污染。

function createCounter(){
    let counter=0
    return {
        increateCounter(){
            counter+=1
        }
        decreateCounter(){
            counter-=1
        }
        getCounter(){
            return counter
        }
    }
}

const counter=createCounter()
counter.increateCounter()
counter.getCounter()

es6 class

class其实就是原型链的语法糖,使用了更简洁的面向对象的语法。

//定义类
class Person{
    constructor(name,age){
        this.name=name
        this.age=age
    }
    sayName(){
        console.log(`my name is ${this.name}`)
    }
}
//定义实例
const personOne=new Person('john', 18)