why don’t have function by commonJS way?

博客探讨了CommonJS方式找不到函数的问题。分析发现代码中存在误解,相关调用实际是对象属性,而调用函数是全局对象属性,会导致错误。还指出使用ES6 export可解决该问题,也给出不使用ES6语法的可行代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

why don’t have function by commonJS way?, have below code:

exports.add = function(a, b) {
    return a + b
}
add(2, 3) //-> ReferenceError: add is not defined

wake up, i understand the origin of problem. exports is shorthand of module.exports, so exports.add actually is module.exports.add, that is prop of Object module.exports. however call add function is a prop of global object actually.
so got a error: ReferenceError: add is not defined. use es6 export should no the problem. below code:

export const add = function(a, b) {
    return a + b
}
add(2, 3) //-> 5

// babel complier to es5

"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
var add = exports.add = function add(a, b) {
    return a + b;
};
add(2, 3);

so we write such code that is no problem if we want don’t to use grammar of es6:

var add = exports.add = function add(a, b) {
    return a + b;
};
add(2, 3);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值