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

Pivotal Cloud Foundry Developer Certification - Logging, Scaling and High Availability

 How do you access application logs? cf logs APP_NAME cf start APP_NAME To see the logs of particular pcf sub system. cf logs APP_NAME | grep "API\|CELL" To exclude particular logs cf logs APP_NAME | grep -v "API\|CELL" To see application events i.e. start, stop, crash etc... cf events APP_NAME To display all the lines in the Loggregator buffer cf logs APP_NAME --recent  What are the components of the Loggregator system? Loggregator is the next generation system for aggregating and streaming logs and metrics from all of the user apps and system components in a Cloud Foundry deployment. Primary use: 1. Tail/dump logs using CLI.  2. Stream to 3rd party log archive and analysis service 3. Operators and admins can access Loggregator Firehouse, the combined stream from all the apps and metrics data. 4. Operators can deploy nozzle to the firehouse.  A nozzle is a component that monitors the Firehose for specified events and metrics,

Kumaoni Song/Poem - Uttarakhand meri matrebhoomi

O Bhumi Teri Jai Jaikaara Myar Himaala O Bhumi Teri Jai Jaikaara Myar Himaala Khwar main koot tyaro hyu jhalako-2 Chhalaki kaali Gangai ki dhaara myara Himaala Himaala kaali Gangai ki dhaara myar Himaala Uttarakhand meri matrebhoomi Matrabhoomi ya meri pitrabhoomi O Bhoomi teri jai jai kaara myar Himaala Himaala teri jai jai kaara myar Himaala Tali tali taraai kuni-2 O kuni mali mali bhabara myar Himaala Himaala Mali mali bhabara myar Himaala Badari Kedara ka dwar chhana-2 Myara kankhal Hariwara myar Himaala Himaala kankhal Haridwara myar Himaala Kaali Dhauli ka bali chhali jaani-2 Bata naan thula kailasha myar himaala  Ho Bata naan thula kailasha myar Himaala Parvati ko myaro mait yen chha-2 Ho yen chha Shivjyu ko saurasa myar Himaala Himaala Shiv jyu ko saurasa myar Himaala Dhan mayedi mero yo janama-2 Himaala teri kokhi mahana myar Himaala Himaala teri kokhi mahana myar Himaala Mari jula to tari julo-2 O eju ail tyara baana myar Himaala-2 Himaala ail tyara

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/