KEMBAR78
Javascript Objects Deep Dive | PPTX
Javascript Objects
--Manish Jangir--
Almost Everything Is Object
In Javascript
I’ll prove it at the end of this presentation
What is an Object?
An object is an unordered list of primitive data types (and sometimes reference
data types) that is stored as a series of name-value pairs. Each item in the list is
called a property (functions are called methods).
Think of the above object is a container that’s holding two name-value pairs in it.
Javascript objects are dynamic that we can create, update and delete more
properties even after its initial definition.
Important: The above example is one way of creating objects. But that’s not
the only way of create an object.
Objects Are Non-Primitive (Reference) Data Types
Object are reference data types that means, they don’t contain the value directly
but the memory reference of the value.
In the above snippet, var first is not containing that object directly. Instead the
object is first stored in memory and that memory reference was given to first. So if
we copy the first to second var, the reference was copied not the value.
Any changes in var second, The will be reflected on var first too.
Ways Of Creating Javascript Objects
There are 3 ways to create Javascript Objects:
1. Object Literal - ({})
2. Object Constructor - (new Object())
3. Function Constructor - (new FunctionName())
Object Literal - {}
The most common and the easiest way to create objects is with the object literal:
Object Constructor - new Object()
The second most common way to create objects is with Object constructor. A
constructor is a function used for initializing new objects. Use the new keyword to
call the constructor.
Function Constructor - new FunctionName()
For simple objects that may only be used once for e.g. storing your application
configuration etc, the previous two methods are sufficient. But what if you want to
create more than one object with similar features. A function constructor is just a
simple javascript function that is able to create multiple objects when called with
new operator.
Function Constructor Example
Don’t Return Anything Non-Primitive
It is highly recommended that you don’t return anything non-primitive data type
from the function constructor otherwise the instance will lose its prototypes.
In the above example, we are returning an another object, so our newly created
instance will be converted into that. There is no issue in returning any string,
boolean, number, null or undefined because they are primitive data types.
Don’t Forget To Put “new” Keyword
If you don’t or forget to put the “new” keyword while creating an object instance,
your constructor function will behave just like a simple and pure function. For e.g.
In the above example, we are not creating the object rather simple calling a pure
function. The function did not return anything, so myBook will be undefined here
and so myBook.name is. Infact we are indirectly modifying the global variables
here as the meaning of “this” in the function is window.
Setting and Getting Object Properties
Javascript Objects properties can be set in 3 different ways. Each way has its own
advantage:
1. Dot Notation
2. Bracket Notation
3. Object.defineProperty (Used rarely but very beneficial)
Dot Notation
In the previous examples, we have used the dot notation to assign the properties
to the object. Although dot notation is very fast but too limited as you can only
assign the property names that a valid identifier or string that start from _, $ or
alphabets.
Bracket Notation
Bracket notation is not much faster than dot notation but it accepts anything as a
key name. If you pass a key in quotes, that is taken as it is. But whatever you put
without any quotes as a key name, the engine will try to get the string value of key
first. Its most useful in case of dynamic property names.
Object.defineProperty() (Used in Rare Cases)
Before moving on this, you must have to know the javascript object property
descriptors. As we saw earlier that objects are non-primitive and mutuable data
types so anyone can change the property values anywhere in the code.
What if you don’t want to let anybody to change the value of a particular property
once it is defined?? There are 5 basic property descriptors:
1. Enumerable
2. Writable
3. Configurable
4. Get
5. Set
Object.defineProperty() - Enumerable
Enumereble properties are those which are hidden in a for...loop, JSON.stringify and Object.keys.
Object.defineProperty() - Writable
It helps us to decide whether the property can be modified or not once the object has been defined.
Practical example : You can never change the value of Math.PI in your code. It will always be 3.14
Object.defineProperty() - Configurable
Configure whether the property can be deleted (Using delete keyword) from object or not.
Object.defineProperty() - Configurable
Configure whether the property can be deleted (Using delete keyword) from object or not.
Everything Is Object in JS
Let’s see some example that will prove that how almost every line of your daily JS code contains an
object.
Continued...
Continued...
Native Objects Provided By Browser
There are a lot of native objects provided by the browser and all the data types and sub-types are just
instances of these native objects. Some of them are listed here:
1. Object
2. Function
3. String
4. Number
5. Boolean
6. Date
7. Regxr
8. Error
9. Math
And the list goes on….
Practice
There are a lot of native objects provided by the browser and all the data types and sub-types are just
instances of these native objects. Some of them are listed here:
1. Object
2. Function
3. String
4. Number
5. Boolean
6. Date
7. Regxr
8. Error
9. Math
And the list goes on….
A Typical Example Of Object
“this”
The Most Frustrating Keyword In Javascript Ever
What will be the output of the following code?
Let’s Make It Extremely Simple
To Know “this” Value, Never Look At Function Body
If you are trying to find the value of “this” in a function by seeing its definition again
and again, you won’t ever find it.
Because the value of “this” is absolutely dynamic and changes at different places.
What we have to do to find “this” is look at HOW THE HELL THE FUNCTION
HAS BEEN CALLED
A Javascript Function Is Usually Called In 4 Ways
1. Direct Invocation ( getFullName() )
2. Invoke as an Object Method ( obj.getFullName() )
3. Invoke using .call function prototype ( getFullName.call(null, 2, 3) )
4. Invoke using .apply function prototype ( getFullName.call(null, [2,3]) )
Let's discuss about each one.
Direct Invocation
When a function is called simply by parenthesis, it is called direct invocation and
the value of this will be always global object (“Window” in browser and “Global” in
Node.js). In strict mode, it will be undefined.
Invoke as Object Method
When a method (or function) is called as a property of any object, then the value
of “this” will always be the caller object.
In the left example, we called two object
methods. The most immediate object which is
calling the functions will be “this” there.
For example, in first call, obj is calling getName
so the value of this will be obj.
But in the second call, obj.info is calling the
function, so the “this” will be obj.info there.
Output?
Returned Inner Function (Closure)
.call Method To Invoke A Function
What if you want to override or use your own object as “this” for function? Then
you will have to call a function manually using .call or .apply function prototypes.
In .call the first argument will always be your context object (object that you want
to put at the place of this) and rest of the parameters are your comma separated
function params that you pass in a normal function.
Example:
.apply Method To Invoke A Function
Call and Apply both are absolutely identical to each other but the difference is, in
.call the function params are passed comma separated and in .apply the function
params are passed as an array. See the example:
.bind To Bind A Context To A Function
Bind is a very useful prototype method in JS world. The enables you to bind a
function the particular context and then call it anywhere anyhow, It’s “this” will not
change anyway. Bind always provides a new function not the reference.
Thank You

Javascript Objects Deep Dive

  • 1.
  • 2.
    Almost Everything IsObject In Javascript I’ll prove it at the end of this presentation
  • 3.
    What is anObject? An object is an unordered list of primitive data types (and sometimes reference data types) that is stored as a series of name-value pairs. Each item in the list is called a property (functions are called methods). Think of the above object is a container that’s holding two name-value pairs in it. Javascript objects are dynamic that we can create, update and delete more properties even after its initial definition. Important: The above example is one way of creating objects. But that’s not the only way of create an object.
  • 4.
    Objects Are Non-Primitive(Reference) Data Types Object are reference data types that means, they don’t contain the value directly but the memory reference of the value. In the above snippet, var first is not containing that object directly. Instead the object is first stored in memory and that memory reference was given to first. So if we copy the first to second var, the reference was copied not the value. Any changes in var second, The will be reflected on var first too.
  • 5.
    Ways Of CreatingJavascript Objects There are 3 ways to create Javascript Objects: 1. Object Literal - ({}) 2. Object Constructor - (new Object()) 3. Function Constructor - (new FunctionName())
  • 6.
    Object Literal -{} The most common and the easiest way to create objects is with the object literal:
  • 7.
    Object Constructor -new Object() The second most common way to create objects is with Object constructor. A constructor is a function used for initializing new objects. Use the new keyword to call the constructor.
  • 8.
    Function Constructor -new FunctionName() For simple objects that may only be used once for e.g. storing your application configuration etc, the previous two methods are sufficient. But what if you want to create more than one object with similar features. A function constructor is just a simple javascript function that is able to create multiple objects when called with new operator.
  • 9.
  • 10.
    Don’t Return AnythingNon-Primitive It is highly recommended that you don’t return anything non-primitive data type from the function constructor otherwise the instance will lose its prototypes. In the above example, we are returning an another object, so our newly created instance will be converted into that. There is no issue in returning any string, boolean, number, null or undefined because they are primitive data types.
  • 11.
    Don’t Forget ToPut “new” Keyword If you don’t or forget to put the “new” keyword while creating an object instance, your constructor function will behave just like a simple and pure function. For e.g. In the above example, we are not creating the object rather simple calling a pure function. The function did not return anything, so myBook will be undefined here and so myBook.name is. Infact we are indirectly modifying the global variables here as the meaning of “this” in the function is window.
  • 12.
    Setting and GettingObject Properties Javascript Objects properties can be set in 3 different ways. Each way has its own advantage: 1. Dot Notation 2. Bracket Notation 3. Object.defineProperty (Used rarely but very beneficial)
  • 13.
    Dot Notation In theprevious examples, we have used the dot notation to assign the properties to the object. Although dot notation is very fast but too limited as you can only assign the property names that a valid identifier or string that start from _, $ or alphabets.
  • 14.
    Bracket Notation Bracket notationis not much faster than dot notation but it accepts anything as a key name. If you pass a key in quotes, that is taken as it is. But whatever you put without any quotes as a key name, the engine will try to get the string value of key first. Its most useful in case of dynamic property names.
  • 15.
    Object.defineProperty() (Used inRare Cases) Before moving on this, you must have to know the javascript object property descriptors. As we saw earlier that objects are non-primitive and mutuable data types so anyone can change the property values anywhere in the code. What if you don’t want to let anybody to change the value of a particular property once it is defined?? There are 5 basic property descriptors: 1. Enumerable 2. Writable 3. Configurable 4. Get 5. Set
  • 16.
    Object.defineProperty() - Enumerable Enumerebleproperties are those which are hidden in a for...loop, JSON.stringify and Object.keys.
  • 17.
    Object.defineProperty() - Writable Ithelps us to decide whether the property can be modified or not once the object has been defined. Practical example : You can never change the value of Math.PI in your code. It will always be 3.14
  • 18.
    Object.defineProperty() - Configurable Configurewhether the property can be deleted (Using delete keyword) from object or not.
  • 19.
    Object.defineProperty() - Configurable Configurewhether the property can be deleted (Using delete keyword) from object or not.
  • 20.
    Everything Is Objectin JS Let’s see some example that will prove that how almost every line of your daily JS code contains an object.
  • 21.
  • 22.
  • 23.
    Native Objects ProvidedBy Browser There are a lot of native objects provided by the browser and all the data types and sub-types are just instances of these native objects. Some of them are listed here: 1. Object 2. Function 3. String 4. Number 5. Boolean 6. Date 7. Regxr 8. Error 9. Math And the list goes on….
  • 24.
    Practice There are alot of native objects provided by the browser and all the data types and sub-types are just instances of these native objects. Some of them are listed here: 1. Object 2. Function 3. String 4. Number 5. Boolean 6. Date 7. Regxr 8. Error 9. Math And the list goes on….
  • 25.
  • 26.
    “this” The Most FrustratingKeyword In Javascript Ever
  • 27.
    What will bethe output of the following code?
  • 28.
    Let’s Make ItExtremely Simple
  • 29.
    To Know “this”Value, Never Look At Function Body If you are trying to find the value of “this” in a function by seeing its definition again and again, you won’t ever find it. Because the value of “this” is absolutely dynamic and changes at different places. What we have to do to find “this” is look at HOW THE HELL THE FUNCTION HAS BEEN CALLED
  • 30.
    A Javascript FunctionIs Usually Called In 4 Ways 1. Direct Invocation ( getFullName() ) 2. Invoke as an Object Method ( obj.getFullName() ) 3. Invoke using .call function prototype ( getFullName.call(null, 2, 3) ) 4. Invoke using .apply function prototype ( getFullName.call(null, [2,3]) ) Let's discuss about each one.
  • 31.
    Direct Invocation When afunction is called simply by parenthesis, it is called direct invocation and the value of this will be always global object (“Window” in browser and “Global” in Node.js). In strict mode, it will be undefined.
  • 32.
    Invoke as ObjectMethod When a method (or function) is called as a property of any object, then the value of “this” will always be the caller object.
  • 33.
    In the leftexample, we called two object methods. The most immediate object which is calling the functions will be “this” there. For example, in first call, obj is calling getName so the value of this will be obj. But in the second call, obj.info is calling the function, so the “this” will be obj.info there.
  • 36.
  • 37.
  • 38.
    .call Method ToInvoke A Function What if you want to override or use your own object as “this” for function? Then you will have to call a function manually using .call or .apply function prototypes. In .call the first argument will always be your context object (object that you want to put at the place of this) and rest of the parameters are your comma separated function params that you pass in a normal function. Example:
  • 39.
    .apply Method ToInvoke A Function Call and Apply both are absolutely identical to each other but the difference is, in .call the function params are passed comma separated and in .apply the function params are passed as an array. See the example:
  • 40.
    .bind To BindA Context To A Function Bind is a very useful prototype method in JS world. The enables you to bind a function the particular context and then call it anywhere anyhow, It’s “this” will not change anyway. Bind always provides a new function not the reference.
  • 41.