Is there any way to avoid the constant use of the this
keyword to access the properties and methods of the current object?
I tried something like in Example 2
, but it doesn't work at all.
Example 1:
<script>
var fruits = {
printApple(){ return "Apple"; },
printBanana(){ return "Banana"; },
printPear(){ return "Pear"; },
printAll(){ return "All Fruits: " + this.printApple() + ", " + this.printBanana() + ", " + this.printPear(); }
}
alert(fruits.printAll());
</script>
Example 2:
(this script doesn't work, don't use it)
<script>
var fruits = {
y(){ return this.fruits; },
printApple(){ return "Apple"; },
printBanana(){ return "Banana"; },
printPear(){ return "Pear"; },
printAll(){ return "All Fruits: " + y.printApple() + ", " + y.printBanana() + ", " + y.printPear(); }
}
alert(fruits.printAll());
</script>