如何将包含方法的对象添加到Array对象中以供项目全局使用
问题原因
- 你直接在
Array.prototype上固定赋值new lapla()实例时,这里的this指向全局上下文,无法绑定到调用时的具体数组实例,拿不到对应数组的内容 lapla类的构造函数没有完成this.array的赋值逻辑- 测试代码的
console.log缺少闭合右括号
正确实现方案
通过给Array.prototype定义动态getter的方式实现,每次访问.awesome属性时,动态生成绑定当前数组的lapla实例:
class Lapla { constructor(array) { // 接收传入的数组挂载到实例 this.array = array } // 数组求和方法 sum = () => this.array.reduce((prev, curr) => prev + curr, 0) } // 给数组原型定义awesome属性的getter Object.defineProperty(Array.prototype, 'awesome', { get() { // getter内的this指向当前调用属性的数组实例 return new Lapla(this) } }) // 测试输出结果为6 console.log([1,2,3].awesome.sum())
补充说明
如果不想污染原生数组原型,可以直接手动创建实例使用,效果一致:
const laplaInstance = new Lapla([1,2,3]) console.log(laplaInstance.sum()) // 输出6
内容的提问来源于stack exchange,提问作者Andrew Naem
相关产品推荐
相关产品推荐

