JAVASCRIPT

Object

다미르 2019. 9. 2. 20:49

1. Type of JS

 

Each language has ‘Primitive type’.

JS has 6 primitive types described below :  

- Boolean

- Null

- Undefined

- Number

- String

- Symbol (added in ESMA 6)

Except for primitive types, everything in JS is an ‘Object’.


 2. What is the Object?

 

It is normalized, formalized and 'abstracted' one of reality.

For example, let's suppose that we build a human to object.

 

First, what does Human have?

We have common things such as legs, arm, head, nationality, sex, etc.

Those things are called 'property'.

 

Next, what does human do?

We walk, eat, sleep, work, etc.

Those actions are called 'method'.

 

We analyze common things(property) and actions(method) of Human

and design an abstract human.

It is a fundamental concept of an object in an object-oriented language.

 

So the object is a collection of ‘property’ and ‘method’.

- Property: Contains information of Object in key–value format

- Method: ‘Action’ of Object

What is different between Function and Method?

It seems similar but there is a huge difference.

A method is called by ‘Object’ which defines an action,

But Function is an ‘Object’ itself.

We will see the details of Function in the next post.

Just remember that Function is a special Object in JS.

 

Just take a look simple example of Object.

var Person = {
	'name' : 'Nam',
	'nationality' : 'Korea',
	'sex' : 'male',
	'age' : 26,
	// .. more properties to describe one person
	// method
	'walk' : function() {
		console.log(this.name + " walks");
    }
}

3. Type of Object

 

- built-in: Loaded immediately when JS engine is started.

             Ex) Number, Array, Object

- Native: Objects provided by JS engine(normally browser)

            Ex) DOM

- Custom: Objects you defined

DO NOT CONFUSE primitive type ‘Number’ and ‘Number’ Object.

We also see the details in the next post.


4. How to create an Object?

 

There are two ways to create an Object.

- 'Literal' : create Object using javascript expression. We saw it above.

- 'Constructor' : Actually all Objects are created by Constructor.

Above example is equals to this:

var Person = new Object();
Person.name = 'Nam';
// other properties..
// method
Person.walk = function() {
	console.log(this.name + " walks");
}

When you create Object using 'Literal' expression, actually it calls the constructor(in this case Object) and returns an instance of Object.

 

Well, ‘Literal’ way is more preferred by the following reasons :

- easy to read

- faster

- and safe(because constructor function can be overridden)


5. Appendix

JS engine loads default Object constructor Object() and Object.prototype.

And this is the top-level of Object in JS.