balamuruganv
balamuruganv

Reputation: 133

difference between normal function declaration and inside return block function declaration in Javascript

What is the difference between normal function declaration and inside return block function declaration in Javascript.

Below code normal function name : updatename, inside function name : changeName

function person(firstName,lastName,age,eyeColor) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.eyeColor = eyeColor;

    this.updatename = function (name) {
        this.lastName = name;
    }

    return {

        'changeName' :  function (name) {
            this.lastName = name;
        }
    }; 

}
var myMother = new person("Sally","Rally",48,"green");

console.dir(myMother);

console.log(typeof(myMother.changeName));

console.log(typeof(myMother.updatename));

myMother.changeName("Doe");

Upvotes: 1

Views: 60

Answers (1)

user663031
user663031

Reputation:

If you return an object from a function, then invoke that as a constructor with new, the original this of the function is THROWN AWAY AND IGNORED AND LOST FOREVER. In other words, the value of this.firstName is never again accessible in this world. What are you trying to accomplish by returning that object literal?

What is the difference between normal function declaration and inside return block function declaration in JavaScript?

The difference (assuming you mean method declaration) is that the normal declaration does what you would normally imagine it would do. The "inside return block function declaration" overrides and cancels the original value of this, and instead returns JUST THAT OBJECT with a single method, which is probably not what you want.

Upvotes: 1

Related Questions