JavaScript对象字面量:如何替换this关键字访问对象成员
避免频繁使用
this访问对象属性/方法的可行方案 你示例2的写法报错是必然的——y是fruits对象的一个方法,直接在printAll里写y.printApple()时,JS引擎会去全局作用域查找y变量,根本找不到;而且y()里返回this.fruits,这里的this指向fruits对象,但fruits本身并没有fruits这个属性,就算能调用y(),拿到的也是undefined,自然没法访问目标方法。
下面是几种实用的替代方案:
方法1:在方法内部解构当前对象的方法
在需要调用多个内部方法的函数里,一次性从this解构出所需方法,后续直接用方法名调用,不用反复写this:
<script> var fruits = { printApple(){ return "Apple"; }, printBanana(){ return "Banana"; }, printPear(){ return "Pear"; }, printAll(){ const { printApple, printBanana, printPear } = this; return "All Fruits: " + printApple() + ", " + printBanana() + ", " + printPear(); } } alert(fruits.printAll()); </script>
方法2:构造函数+变量保存this引用
如果你的对象是通过构造函数创建的,可以在构造函数内把this赋值给一个变量(比如self),后续所有方法都用这个变量代替this:
<script> function Fruits() { const self = this; self.printApple = function() { return "Apple"; }; self.printBanana = function() { return "Banana"; }; self.printPear = function() { return "Pear"; }; self.printAll = function() { return "All Fruits: " + self.printApple() + ", " + self.printBanana() + ", " + self.printPear(); }; } const fruits = new Fruits(); alert(fruits.printAll()); </script>
方法3:ES6类+解构(或箭头方法)
使用类语法时,同样可以在方法内部解构this的方法;如果运行环境支持类字段提案,也可以用箭头方法——箭头方法的this会绑定类实例,无需担心指向问题:
<script> class Fruits { printApple() { return "Apple"; } printBanana() { return "Banana"; } printPear() { return "Pear"; } printAll() { const { printApple, printBanana, printPear } = this; return `All Fruits: ${printApple()}, ${printBanana()}, ${printPear()}`; } } const fruits = new Fruits(); alert(fruits.printAll()); </script>
内容的提问来源于stack exchange,提问作者brut65
相关产品推荐
相关产品推荐

