简体   繁体   中英

Where JavaScript variable is located?

I'm new to JavaScript and this seems very strange for me...

function Employee() {}
var emp = new Employee();
emp.name = "John Doe";
alert(emp.name);

I don't even know what keyword to search about this Where will, the "name" variable, be located? global namespace, public property, or whatever?

You've got a couple things going on here that can easily trip up someone new to Javascript. Let's breakdown the script line by line.

function Employee() {}

This is defining a new constructor function that will create Employee objects. Currently, the function does very little.

var emp = new Employee();

Here, we instantiate an Employee object with the new keyword and assign it to the variable emp . It will be contained within whatever scope it is declared--in this case, the global scope.

emp.name = "John Doe";

We set the property name of the local object emp to be "John Doe." This might seem strange if you're coming from a language that requires you to be more explicit about objects. Javascript doesn't care that the "name" property was never mentioned in your constructor object. So, it's totally cool to assign the "name" property on emp . One downside to this is that if you make other instances of Employee they won't necessarily have a name property.

alert(emp.name);

Use the browser's alert function to show us the name "John Doe."

So, to answer explicitly, name is a "public" property of emp (an instance of Employee), in the sense that other people can read/write it directly. Javascript doesn't have a way of explicitly declaring things public or private. To get that kind of behavior, you have to rely on design patterns. If you want to mimic public/private properties, you might consider the "Revealing" pattern, which Addy Osmani lays out in his really great book Learning Javascript Design Patterns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM