2

I am a noob to javascript.

I wanted to know why do we have to use this while defining properties and functions in the javascript. for example

   function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    };
}

var apple = new Apple('macintosh');
apple.color = "reddish";
alert(apple.getInfo());

I know this refers to the object that calls the class. We used this in c++ and java. we defines a class something like this

class apple {
        char type ;
        char color ;
        returntype getInfo (){
          this.color = 'red';
           this.type = 'something'

    }

I thought its weird to have this in javascript for declaring properties also. Any reason behind this ?

3
  • It was modeled to have similar syntax to Java. Ask the designers. Commented Jul 24, 2013 at 17:07
  • It's the same thing as Java, except it's optional to use this in Java, and JavaScript doesn't explicitly have a "constructor" function separate from definitions. What's your real question? Commented Jul 24, 2013 at 17:15
  • If you think this is weird then better not read about prototypes. Commented Jul 24, 2013 at 18:10

2 Answers 2

1

There are no classes in JavaScript. Everything is an object. Therefore, you need to manipulate the object.

When calling function with new: this will refer to a newly created object that you can edit.

If you call your function without new, then this will actually be window (browser) or global (server-side) in your example.

To add new fields to the object you normally do: object.newfield = somevalue, but here that object is stored in variable this.

Process is similar to:

new function -> create new object -> pass it as "this" to function -> function works -> return updated "this"

function works part is where your function code is actually executed.

Sign up to request clarification or add additional context in comments.

Comments

0

It's a weird JavaScript thing, where everything is objects. The "class" in JavaScript is really just an object's constructor. If you call it without the this (just Apple() or MyClass()), variables are just local variables. When you start adding OOP, you get a scenario where you need to be able to differentiate between object properties and local variables to the constructor (or method's, for that matter). Therefore, the this keyword is used to point to a reference to the current object in question (so you are accessing the properties of the object, not the properties of the current scope of the function)

Alternatively.. because someone said so and we, the programmers, have to live with it ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.