Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use this in javascript OO?

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()?
   }
}
like image 224
Ali Avatar asked Jul 17 '09 16:07

Ali


People also ask

When should I use this in JavaScript?

“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.

What is OO used for?

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.

What is OO in JavaScript?

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.

What are the advantages of OO?

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.


2 Answers

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.)

like image 173
Blixt Avatar answered Sep 18 '22 05:09

Blixt


I have found 3 Ways to define a javascript class helpful.

like image 35
Ali Avatar answered Sep 18 '22 05:09

Ali