简体   繁体   中英

If everything is an “object” in javascript isn't “creating objects” redundant?

I've heard that "everything in javascript is an object" according to many tutorials and people across the internet. However, I'm also well aware of several methods to "create objects", such as a constructor, a factory or an object literal.

What I don't understand is...if "everything is an object" why should I have to "create one"? Isn't the creation of a variable the creation of "an object"? Isn't the creation of a function the creation of an object?

What are we really creating when we say we are "creating objects"?

What I don't understand is...if "everything is an object" why should I have to "create one"?Isn't the creation of a variable the creation of "an object"?

No... Variables are kind of like names for things. It's like saying "If we want a baby, we already know we'll call it Jamie, why should we need sex?"

Variables just point at objects, but are not objects themselves. Comments are not objects either. Nor is the for keyword, nor curly braces, nor the assignment operator = . In fact, most things in JavaScript are, really, not objects.

However, everything that you can assign to your variable, is. Except integers. And other numbers. And truth values. And some other stuff we call "primitive types". However they kind of behave like objects (as in, you can call methods on them). So... not nearly everything.

So... when you say var a = {} , what you are doing is really...

  • creating an empty object, {}
  • declaring a variable a
  • telling the variable a that it should point to that empty object.

When you say var b = a , you say "I want to have a variable b , and I want it to point at the same thing a already is. It's like saying "We have John, that's this guy here. Let's also call him 'Prettyboy'." From then on, you have two names for the same object. But giving John another name is not making another human.

First of all, not everything is an object in JavaScript . There are six primitive types and an object type. Every piece of data must fall within one of these types.

Second of all, and 'object' is a type, when you 'create an object', you are creating a modified copy of that type. This is similar to creating an instance of a class if you come from a more classical object-oriented programming (OOP) language.

Compare that to a real-world example - there are things called 'Cars', so why do we need to create more cars?

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