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>
2
Answers
The use of
this
like many languages is unavoidable. especially when you need to access properties or methods of the same object.this
keyword is special variable that every execution context gets and it automatically set by the JS engine.Your example 2 – the script does not work because
y
is not defined in the global context.Basically, "NO". You do need to reference some object and then run the method on it.
"this is a question, for the example 2 how can i avoid the constant use of the this keyword, and replace for something more shortable. Or simply do not use."
you could use an optional parameter, defaulting to this as below: