若依js版前端封装方法的例子
时间: 2023-07-26 13:15:30 浏览: 91
以下是js版前端封装方法的一些例子:
1. 模块化封装
```javascript
// user.js
function login(username, password) {
// 登录操作
}
module.exports = {
login: login
};
// index.js
const user = require('./user.js');
user.login('user', 'password');
```
2. 面向对象封装
```javascript
// person.js
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}, I'm ${this.age} years old.`);
};
module.exports = Person;
// index.js
const Person = require('./person.js');
const person = new Person('Tom', 18);
person.sayHello();
```
3. 工具化封装
```javascript
// utils.js
function formatDate(date) {
// 格式化日期
}
module.exports = {
formatDate: formatDate
};
// index.js
const utils = require('./utils.js');
const now = new Date();
console.log(utils.formatDate(now));
```
4. 函数式封装
```javascript
// add.js
function add(a, b) {
return a + b;
}
module.exports = add;
// index.js
const add = require('./add.js');
const result = add(1, 2);
console.log(result);
```
这些例子只是js版前端封装方法的一部分,实际上还有很多其他的封装方法和应用场景。在实际开发中,可以根据具体需求选择适合的封装方法。
阅读全文
相关推荐


















