JavaScript函数存储数组调用init方法报not a function错误如何解决
问题原因与解决方案
原代码核心问题
init是定义在myFunc函数内部的私有函数,没有挂载到myFunc对象上,无法直接通过myFunc.init()调用,因此会抛出TypeError: myFunc.init is not a function错误- 拼写错误:属性名
lenght应为length,运行时会触发属性不存在的报错 - 变量作用域错误:
init内部直接访问myArr时,既没有绑定到this,也没有指向外层作用域的变量,会抛出变量未定义的错误 - 普通函数调用模式下
this指向全局对象,会意外污染全局作用域
修复方案
方案1:静态属性实现(贴合原有写法)
直接将数组和init方法挂载为myFunc的静态属性,保留你原有调用逻辑:
function myFunc() { // 静态属性存储数组,避免重复初始化 if (!myFunc.myArr) { myFunc.myArr = []; } return myFunc.myArr; } // 把init挂载为myFunc的静态方法 myFunc.init = function() { const arr = myFunc(); if (arr.length === 0) { arr.push(1, 2, 3); console.log("initialized now"); } else { console.log("initialized already. Arrlength: ", arr.length); } } // 调用逻辑和你原有写法一致 myFunc.init() console.log(myFunc());
运行输出完全符合你的预期:
initialized now [ 1, 2, 3 ]
如果需要触发第二次的初始化完成日志,再加一次myFunc.init()调用即可。
方案2:闭包实现(私有变量更安全)
如果不想让存储的数组被外部直接修改,可以用立即执行函数创建闭包封装私有变量:
const myFunc = (function() { // 私有数组,外部无法直接访问修改 const myArr = []; function init() { if (myArr.length === 0) { myArr.push(1, 2, 3); console.log("initialized now"); } else { console.log("initialized already. Arrlength: ", myArr.length); } } const publicApi = function() { // 返回数组副本,避免外部修改原存储值,不需要可直接返回myArr return [...myArr]; } publicApi.init = init; return publicApi; })(); myFunc.init() myFunc.init() console.log(myFunc());
运行输出:
initialized now initialized already. Arrlength: 3 [ 1, 2, 3 ]
内容的提问来源于stack exchange,提问作者rustyBucketBay
相关产品推荐
相关产品推荐

