You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 22:42:24