In Javascript OO, when should I use the this
keyword?
Also, if I want to call a method of a class from another method of the same class, should I use this
or just the name of the function? E.g is this correct?
function Foo()
{
this.bar= function()
{
alert('bar');
}
this.baz= function()
{
this.bar(); //should I use this.bar() or just bar()?
}
}
“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.
It is used to structure a software program into simple, reusable pieces of code blueprints (usually called classes), which are used to create individual instances of objects. There are many object-oriented programming languages including JavaScript, C++, Java, and Python.
Object-Oriented Programming is a way of writing code that allows you to create different objects from a common object. The common object is usually called a blueprint while the created objects are called instances. Each instance has properties that are not shared with other instances.
Some of the advantages of object-oriented programming include: Improved software-development productivity: Object-oriented programming is modular, as it provides separation of duties in object-based program development. It is also extensible, as objects can be extended to include new attributes and behaviors.
When it comes to "object-oriented" JavaScript, here's a nice guide Mark Dickinson here on SO linked to: Private Members in JavaScript. It does go into detail about some other stuff you don't really need now, but once you understand how JavaScript works, you'll see that it's quite different from your ordinary object-oriented language when it comes to things like what this
really means.
I'd say that in your case, you should definitely use this
, but maybe your functions should be in the prototype
part of your "class" (this avoids redefining the function every time a new instance is created.)
I have found 3 Ways to define a javascript class helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With