user5283721 user5283721 - 4 years ago 82
Javascript Question

Understanding javascript in detail

I am a beginner in javascript I am finding one concept very confusing.Consider the code below:

var person = {
firstName :"Penelope",
lastName :"Barrymore",
// Since the "this" keyword is used inside the showFullName method below, and the showFullName method is defined on the person object,​
// "this" will have the value of the person object because the person object will invoke showFullName ()​
showFullName:function () {
console.log (this.firstName + " " + this.lastName);
}

}

person.showFullName (); // Penelope Barrymore


Is person a class or function or just a variable?
If assuming that person is a class, is the code
person.showFullName ();
the right way of invoking it,
because in C# or anyother language we write

person perObj = new person();
perObj.showFullName();

Answer Source

person is an object. It has 3 properties, named firstName, lastName, and showFullName. The first two properties contain strings. The last property contains a function.

When you call a function with the syntax <expression>.<function>(<arguments>), where <expression> evaluates to an object and <function> is the name of one of its properties, then while the function is running the special variable this is set to the object. That's how this.firstName and this.lastName are able to access those properties of the object.

This feature is not very useful when there's just a single object, since it could easily just use the person variable. But you could use the same function for multiple objects.

function showFull() {
    console.log(this.firstName + " " + this.lastName);
}
var person1 = {
    firstName: "Penelope",
    lastName: "Barrymore",
    showFullName: showFull
};
var person2 = {
    firstName: "John",
    lastName: "Smith",
    showFullName: showFull
}
person1.showFullName(); // Penelope Barrymore
person2.showFullName(); // John Smith
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download