1

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");
7
  • 1
    That's not a return block. It's an object literal. Commented Aug 31, 2016 at 6:45
  • if comment out normal function and execute above code typeof(myMother.changeName) returning function. Commented Aug 31, 2016 at 6:47
  • They are both functions. There is no difference from language perspective. They come from different scopes, though but that's about it. Commented Aug 31, 2016 at 6:51
  • 1
    When you call a function with new the function should not return anything. The new keyword will return the function's this. I repeat: the new keyword returns an object, not the constructor. Commented Aug 31, 2016 at 6:52
  • yep, js is not allowing to declare both type of function if i declare return block code is overriding normal block type will be undefined Commented Aug 31, 2016 at 6:53

1 Answer 1

1

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.

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

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.