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>
Seems the most idiomatic way and easy way is to use function constructors (hard objects). Actually I prefer it over prototypes and it's very good for the mixin design pattern.
Regarding your question - no nice object literal alternative exists but you could use an anonymous constructor function:
Also tested on thousands of object against prototypes and the difference in performance is negligible for the most cases.
One another benefit that you don't care about proper
thisbinding anymore and can pass method refs safely, because thethisbinding happens in the constructor.