JS封装函数代码
以下是一个示例 JavaScript 函数的封装代码:
// 定义一个函数,计算两个数字的和
function add(a, b) {
return a + b;
}
// 将函数封装成对象,并暴露出去
const calculator = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
},
multiply: function(a, b) {
return a * b;
},
divide: function(a, b) {
return a / b;
}
};
// 使用封装好的函数
console.log(calculator.add(2, 3)); // 输出 5
console.log(calculator.subtract(5, 2)); // 输出 3
console.log(calculator.multiply(2, 4)); // 输出 8
console.log(calculator.divide(10, 2)); // 输出 5
在这个示例中,我们定义了一个简单的加法函数 add。然后,我们把这个函数封装成了一个对象 calculator,并暴露出去,使得其他代码可以访问它的四个方法:add、subtract、multiply 和 divide。最后,我们使用了这些封装好的函数,得到了预期的结果。
原文地址: https://www.cveoy.top/t/topic/bfik 著作权归作者所有。请勿转载和采集!