Skip to main content

Objects are King in JavaScript

"everything" is an object in Javascript
  • Booleans can be objects (or primitive data treated as objects)
  • Numbers can be objects (or primitive data treated as objects)
  • Strings can be objects (or primitive data treated as objects)
  • Dates - objects
  • Maths - objects
  • Regular expressions - objects
  • Arrays - objects
  • Functions - objects
  • Objects - objects

All values, except primitive values, are objects.

Primitive values are: strings ("Bipin Joshi"), numbers (3.14), true, false, null, and undefined.  

3 Ways 2 Create :
a. Using an object literal.
       var emp = {firstName:"Bipin", lastName:"Joshi", age:32,  id:1};   
b. With the keyword new.
      
        var emp =  new Object();
        emp.firstName = "Bipin";
        emp.lastName = "Joshi";
        emp.age = 32;
        emp.id = 1
c. Java way.

       function employee(first, last, age, id) {
            this.firstName = first;
            this.lastName = last;
            this.age = age;
            this.id= id;
       }
       var emp1= new employee("Bipin", "Joshi", 32, "1");
       var emp2= new employee("xx", "xx", xx, "2");



The this Keyword

this, is the object that "owns" the JavaScript code.
this, when used in a function, is the object that "owns" the function.
this, when used in an object, is the object itself.
this keyword in an object constructor does not have a value. It is only a substitute for the new object.
this will become the new object when the constructor is used to create an object.



Built-in JavaScript Constructors

Built-in constructors for native objects:


var x1 = new Object();    // A new Object object  
var x2 = new String();    // A new String object  
var x3 = new Number();    // A new Number object 
var x4 = new Boolean()    // A new Boolean object  
var x5 = new Array();     // A new Array object 
var x6 = new RegExp();    // A new RegExp object  
var x7 = new Function();  // A new Function object 
var x8 = new Date();      // A new Date object 
 But we use primitive values  as :
var x1 = {};            // new object 
var x2 = "";            // new primitive string 
var x3 = 0;             // new primitive number  
var x4 = false;         // new primitive boolean 
var x5 = [];            // new array object 
var x6 = /()/           // new regexp object  
var x7 = function(){};  // new function object

JavaScript Objects are Mutable

They are addressed by reference, not by value.

If y is an object, the following statement will not create a copy of y:


var x = y;  // This will not create a copy of y.
The object x is not a copy of y. It is y. Both x and y points to the same object.
Any changes to y will also change x, because x and y are the same object.

Example

var emp= {firstName:"Bipin", lastName:"Joshi", age:32, id:"12"}

var x = emp;
x.age = 10;           // This will change both x.age and emp.age


JavaScript Properties

Properties are the values associated with a object.
A JavaScript object is a collection of unordered properties.
Properties can usually be changed, added, and deleted, but some are read only.

Accessing JavaScript Properties

The syntax for accessing the property of an object is:
objectName.property          // emp.age
or
objectName["property"]       // emp["age"]
or
objectName[expression]       // x = "age"; emp[x]

JavaScript for...in Loop

The JavaScript for...in statement loops through the properties of an object.

Syntax

for (variable in object) {
    code to be executed
}
The block of code inside of the for...in loop will be executed once for each property.
Looping through the properties of an object:

Example

var emp= {fname:"Bipin", lname:"Joshi", age:32};

for (x in emp) {
    txt += emp[x];
}
Will print : Bipin Joshi 32

Accessing Object Methods

You create an object method with the following syntax:

methodName : function() { code lines }

You access an object method with the following syntax:

objectName.methodName()
Example:
<!DOCTYPE html>
<html>
<body>

<p>Creating and using an object method.</p>

<p>An object method is stored as a function definition,
in an object property.</p>

<p id="demo"></p>

<script>
var emp= {
    firstName: "Bipin",
    lastName : "Joshi",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};

document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>

FYI : Java script built in objects have built-in methods too, example:

Boolean Methods

Here is a list of each method and its description.
MethodDescription
toSource()Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object.
toString()Returns a string of either "true" or "false" depending upon the value of the object.
valueOf()Returns the primitive value of the Boolean object.

String Methods

few are :
MethodDescription
charAt()Returns the character at the specified index.
charCodeAt()Returns a number indicating the Unicode value of the character at the given index.
concat()Combines the text of two strings and returns a new string.
indexOf()Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
lastIndexOf()Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
localeCompare()Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
length()Returns the length of the string.


JavaScript Prototypes

Every JavaScript object has a prototype. The prototype is also an object.

All JavaScript objects inherit the properties and methods from their prototype.
Objects created using an object literal, or with new Object(), inherit from a prototype called Object.prototype.
Objects created with new Date() inherit the Date.prototype.
The Object.prototype is on the top of the prototype chain.
All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the Object.prototype.

The JavaScript prototype property allows you to add new properties to an existing prototype:

Example

function person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
person.prototype.nationality = "English";


The JavaScript prototype property also allows you to add new methods to an existing prototype:

Example

function person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
person.prototype.name = function() {
    return this.firstName + " " + this.lastName;
};

More on JavaScript Prototypes in upcoming post :)

Comments

Popular posts from this blog

OpenStack - Conceptual architecture showing the relationship b/w services

AWS vs Openstack comparison https://redhatstackblog.redhat.com/2015/05/13/public-vs-private-amazon-compared-to-openstack/

Pivotal Cloud Foundry Developer Certification - Managed and User-Provided Services

1. What is a service? Can you name some examples? Services are cloud native apps dependencies. Consider S ervice as a factory that delivers service instances. Two types: 1. Managed services Cloud Foundry offers a marketplace of services, from which users can provision reserved resources on-demand. Examples of resources services provide include databases on a shared or dedicated server, or accounts on a SaaS application.  Example: my-sql, rabbitmq, redis etc... 2. User provided services User provided services provides the metadata to connect to the system outside the cloud. These services are not available in market place. This are custom services i.e. connecting to your own external DB or any other service outside the cloud i.e. erp etc.. Command to list the service instances in your space: cf services To see details of particular service cf service SERVICE_INSTANCE_NAME What is the “marketplace”? Does it show all services?  The Pivotal Cloud F...

Kumaoni Song/Poem - Aaj ka dina

Aaj ka dina,  Tu holi ghar pana O yaad aali, maikani tyaar bina O yaad aali, maikani tyaar bina Ghutghutu maike, Batuli lagaye Ghutghutu maike, Batuli lagaye O yaad aali, maikani tyaar bina O yaad aali, maikani tyaar bina Aankho me aanshu, teri holi Mai pardesha, Tu ghar holi Ghutghutu maike, Batuli lagaye Ghutghutu maike, Batuli lagaye O yaad aali, maikani tyaar bina O yaad aali, maikani tyaar bina Aaj ka dina,  Tu holi ghar pana