学习数组解构时调用对象方法触发Uncaught TypeError错误求助
解决对象方法中箭头函数导致的this指向错误问题
你的错误根源是使用箭头函数定义对象的order方法。箭头函数没有独立的this绑定,它会继承外层作用域的this值——在这个场景里,外层是全局作用域,所以this指向全局对象(浏览器中是window,Node.js中是globalThis),而全局对象不存在starterMenu和mainMenu属性,因此尝试读取this.starterMenu[2]时,就会抛出"Cannot read properties of undefined (reading '2')"的错误。
修复方案
把箭头函数替换为普通函数表达式,或者使用ES6的对象方法简写形式,这样方法内部的this会自动指向调用它的restaurant对象:
方式1:ES6方法简写(推荐)
const restaurant = { name: 'Classico Italiano', location: 'Via Angelo Tavanti 23, Firenze, Italy', categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'], starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'], mainMenu: ['Pizza', 'Pasta', 'Risotto'], // 改用方法简写,this指向调用该方法的restaurant对象 order(starterIndex, mainIndex) { return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]]; }, }; console.log(restaurant.order(2, 2)); // 输出: ['Garlic Bread', 'Risotto']
方式2:普通函数表达式
const restaurant = { // 保留其他属性不变 order: function(starterIndex, mainIndex) { return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]]; }, };
验证结果
修改后调用restaurant.order(2, 2),会正确返回starterMenu索引2的元素Garlic Bread和mainMenu索引2的元素Risotto,符合你的预期。
内容的提问来源于stack exchange,提问作者somerandomgamer
相关产品推荐
相关产品推荐

