Question on the use of 'this.'


#1

Even after reading the explanation on the use of 'this.', I still don't quite understand what is its use. So can somebody help me to explain?

Is this

function Person(name,age) {
  name: name,
  age: age
}

the same as

function Person(name,age) {
  this.name = name;
  this.age = age
}

?


#2

No it isn't, and it won't work either. An object constructor (which is what you have there) is a function which creates an object inside the identifier, it is not the object itself, it's simply a structure for one.

//Literal Notation Example
var empty = {
    property: 'value'
};

//Dot Notation Example
empty.property = 'value';

//Object Constructor
//Define Constructor Structure (haha, it rhymes!)
function Constructor (parameter, paramutter) {
    //Add properties to this object using dot notation method
    this.property = parameter;
    this.properto = paramutter;
}

//Call constructor to identifier
var object = new Constructor('Prop', 'Prup');

Real quick, the this keyword refers to an object. Real quick, there's a difference between the two notation methods by which you can add properties to an object, literal notation defines them up front on creation, dot notation applies them later on by assuming that if you're applying a value to a property that doesn't exist, it'll make one, if it does exist, you'll simply overwrite the existing property.

In a constructor, you're basically saying: Here is the structure for this object, it'll have this and this properties, and I want to use these parameters here and here.

When you declare a new instance of that constructor on an identifier you're basically saying this: I want this structure to be represented inside this variable name.

Think of it this way, a constructor is a skeleton, which you're shoving into a sack of skin. Now the function name is not the same as the variable name. As you have your function Person constructor you would type this.

var Mary = new Person('Mary', 35);

This doesn't make sense because we're asking for a name parameter. How else would you use this? Maybe the object is something more objective than a person's name, maybe it's a title.

var boss = new Person('Mary', 35);

You can also use the this keyword to refer to your object inside itself. Rather than typing

var LIS = {
    firstName = 'Kate';
    fullName = empty.firstName + 'Marsh';
}

You could do this

var LIS = {
    firstName = 'Kate';
    fullName = this.firstName + ' Marsh';
}

So I hope this helps you to understand how the this keyword plays a role in objects and their constructors.


"this" keyword Doubt in JAVASCRIPT