使用含this关键字的方法为对象添加属性失败求助
问题解决:对象方法中this指向错误导致无法添加属性
你这段代码无法正常运行的核心原因是箭头函数不会绑定自身的this——箭头函数的this继承自外层作用域,这里外层是全局作用域,所以调用setBestFriend和setNumOfFriends时,this指向的是全局对象(浏览器环境为window,Node.js环境为global,严格模式下是undefined),既找不到this.friends,也没法把bestFriend和numOfFriends绑定到siddhu对象上。
最简单的修复方案:替换为普通函数
把对象里的箭头函数改成普通函数即可,普通函数作为对象方法调用时,this会自动指向调用它的对象,完全不用硬编码对象名,复制代码时只需要修改对象本身的属性值就行:
const siddhu = { name: 'Siddhu', friends: ['Dylan', 'Jordans', 'Aathi'], setBestFriend() { this.bestFriend = this.friends[0]; }, setNumOfFriends() { this.numOfFriends = this.friends.length; }, } siddhu.setBestFriend() siddhu.setNumOfFriends() console.log(`${siddhu.name} has ${siddhu.numOfFriends} friends, and his best friend is ${siddhu.bestFriend}`);
更适合复用的方案:使用类/构造函数
如果需要多次创建类似的对象,重复复制对象结构太麻烦,推荐用类来封装属性和方法,所有实例都会自动继承类的方法,复用性更强:
class Person { constructor(name, friends) { this.name = name; this.friends = friends; } setBestFriend() { this.bestFriend = this.friends[0]; } setNumOfFriends() { this.numOfFriends = this.friends.length; } } // 创建第一个实例 const siddhu = new Person('Siddhu', ['Dylan', 'Jordans', 'Aathi']); siddhu.setBestFriend(); siddhu.setNumOfFriends(); console.log(`${siddhu.name} has ${siddhu.numOfFriends} friends, and his best friend is ${siddhu.bestFriend}`); // 创建第二个实例,直接复用方法 const alice = new Person('Alice', ['Bob', 'Charlie']); alice.setBestFriend(); alice.setNumOfFriends(); console.log(`${alice.name} has ${alice.numOfFriends} friends, and her best friend is ${alice.bestFriend}`);
内容的提问来源于stack exchange,提问作者user17259560
相关产品推荐
相关产品推荐

