JavaScript中如何为函数normalFunction的原型添加属性?
正确为函数原型添加属性的方法
你的代码问题出在先操作函数原型,后声明函数——虽然JS函数声明会提升,但这种写法不符合逻辑顺序,也容易在复杂场景下出问题。正确的做法是先声明函数,再修改它的原型属性:
// 先声明函数 function normalFunction() { } // 再给原型添加属性 normalFunction.prototype.helloWorld = 'hello world' function helloWorld() { return 'hello world' }
补充说明
如果要确保normalFunction一定是函数(避免被意外覆盖为非函数类型),可以加个类型检查:
function normalFunction() { } if (typeof normalFunction === 'function') { normalFunction.prototype.helloWorld = 'hello world' } function helloWorld() { return 'hello world' }
内容的提问来源于stack exchange,提问作者MKdev
相关产品推荐
相关产品推荐

