Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Mutable Parameter?

This is just a technical question about javascript. In javascript, one member of my group found something odd with javascript object creation. For some reason, the parameters in the object are already treated as members without assigning them to any member variables created in the constructor of the object. The parameters are mutable also as seen in the code block below.

Here's the code to show the testing we have being doing.

function NamedItem(name)
{
    name = 5;

    this.getName = function ()
    {
        return name;
    }
}


document.write(namedItem.getName() + "\n");  //5

Is this legitimate? Is it dangerous?

like image 567
Wes Avatar asked Mar 05 '26 05:03

Wes


1 Answers

That's called a closure.
Nested functions can access variables from their parent function and extend the variables' lifetimes beyond the execution of the parent function.

It has nothing to do with objects.

like image 177
SLaks Avatar answered Mar 07 '26 19:03

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!