0% found this document useful (0 votes)
5 views

Objects in Javascript (1)

The document provides an overview of JavaScript objects, including their creation methods (object literal, instance, and constructor), and methods for manipulating objects and strings. It details various string methods, the JavaScript Date object, Boolean values, and the Window and Document objects, along with their properties and methods. The content serves as a comprehensive guide for understanding and utilizing JavaScript's object-oriented features.

Uploaded by

aashurana9628
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Objects in Javascript (1)

The document provides an overview of JavaScript objects, including their creation methods (object literal, instance, and constructor), and methods for manipulating objects and strings. It details various string methods, the JavaScript Date object, Boolean values, and the Window and Document objects, along with their properties and methods. The content serves as a comprehensive guide for understanding and utilizing JavaScript's object-oriented features.

Uploaded by

aashurana9628
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

JavaScript Objects

A JavaScript object is an entity having state and behavior (properties and method).For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript. JavaScript is template based not class based. Here, we don't create class to get the
object.
But, we direct create objects.

 Creating Objects in JavaScript:-


There are 3 ways to create objects:-
1) By object literal
2) By creating instance of Object directly (using new keyword)
3) By using an object constructor (using new keyword)

1) JavaScript Object by object literal


The syntax of creating object using object literal is given below:

object={property1:value1,property2:value2.....propertyN:valueN}

As you can see, property and value is separated by : (colon).


Let’s see the simple example of creating object in JavaScript.

<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

Output of the above example:


102 Shyam Kumar 40000

2) By creating instance of Object


The syntax of creating object directly is given below:
var objectname=new Object();

Here, new keyword is used to create object.


Let’s see the example of creating object directly.

<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

Output of the above example


101 Ravi 50000

3) By using an Object constructor


Here, you need to create function with arguments. Each argument value can be assigned in the current object by using this keyword.The this keyword refers to
the current object.
The example of creating object by object constructor is given below.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>

Output of the above example


103 Vimal Jaiswal 30000
 Defining method in JavaScript Object:-
We can define method in JavaScript object. But before defining method, we need to add property in the function with same name as method.
The example of defining method in object is given below.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;

this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>

Output of the above example


103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000

 JavaScript Object Methods:-


The various methods of Object are as follows:

S.No Methods Description

1 Object.assign() This method is used to copy enumerable and own properties from a source object to a target object

2 Object.create() This method is used to create a new object with the specified prototype object and properties.
3 Object.defineProperty() This method is used to describe some behavioral attributes of the property.

4 Object.defineProperties() This method is used to create or configure multiple object properties.

5 Object.entries() This method returns an array with arrays of the key, value pairs.

6 Object.freeze() This method prevents existing properties from being removed.

7 Object.getOwnPropertyDescriptor() This method returns a property descriptor for the specified property of the specified object.

8 Object.getOwnPropertyDescriptors() This method returns all own property descriptors of a given object.

9 Object.getOwnPropertyNames() This method returns an array of all properties (enumerable or not) found.

10 Object.getOwnPropertySymbols() This method returns an array of all own symbol key properties.

11 Object.getPrototypeOf() This method returns the prototype of the specified object.

12 Object.is() This method determines whether two values are the same value.

13 Object.isExtensible() This method determines if an object is extensible

14 Object.isFrozen() This method determines if an object was frozen.

15 Object.isSealed() This method determines if an object is sealed.

16 Object.keys() This method returns an array of a given object's own property names.

17 Object.preventExtensions() This method is used to prevent any extensions of an object.

18 Object.seal() This method prevents new properties from being added and marks all existing properties as non-configurable.

19 Object.setPrototypeOf() This method sets the prototype of a specified object to another object.

20 Object.values() This method returns an array of values.


 JavaScript String
The JavaScript string is an object that represents a sequence of characters. There are 2 ways to create string in JavaScript:-
1) By string literal
2) By string object (using new keyword)

1) By string literal
The string literal is created using double quotes. The syntax of creating string using string literal is given below:

var stringname="string value";

Let's see the simple example of creating string literal.

<script>
var str="This is string literal";
document.write(str);
</script>

Output:
This is string literal

2) By string object (using new keyword)


The syntax of creating string object using new keyword is given below:Here, new keyword is used to create instance of string.

var stringname=new String("string literal");

Let's see the example of creating string in JavaScript by new keyword.

<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>

Output:
hello javascript string
 JavaScript String Methods:-
Let's see the list of JavaScript string methods with examples.

Methods Description

charAt() It provides the char value present at the specified index.

charCodeAt() It provides the Unicode value of a character present at the specified index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given string.

lastIndexOf() It provides the position of a char value present in the given string by searching a character from the last position.

search() It searches a specified regular expression in a given string and returns its position if a match occurs.

match() It searches a specified regular expression in a given string and returns that regular expression if a match occurs.

replace() It replaces a given string with the specified replacement.

substr() It is used to fetch the part of the given string on the basis of the specified starting position and length.

substring() It is used to fetch the part of the given string on the basis of the specified index.

slice() It is used to fetch the part of the given string. It allows us to assign positive as well negative index.

toLowerCase() It converts the given string into lowercase letter.

toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host current locale.

toUpperCase() It converts the given string into uppercase letter.

toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host current locale.

toString() It provides a string representing the particular object.


valueOf() It provides the primitive value of string object.

split() It splits a string into substring array, then returns that newly created array.

trim() It trims the white space from the left and right side of the string.

 JavaScript String charAt(index) Method


The JavaScript String charAt() method returns the character at the given index.

<script>
var str="javascript";
document.write(str.charAt(2));
</script>

Output: v

 JavaScript String concat(str) Method


The JavaScript String concat(str) method concatenates or joins two strings.

<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>

Output:
javascript concat example
 JavaScript String indexOf(str) Method
The JavaScript String indexOf(str) method returns the index position of the given string.

<script>
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
Output:
11

 JavaScript String lastIndexOf(str) Method


The JavaScript String lastIndexOf(str) method returns the last index position of the given string.

<script>
var s1="javascript from javatpoint indexof";
var n=s1.lastIndexOf("java");
document.write(n);
</script>

Output:
16

 JavaScript String toLowerCase() Method


The JavaScript String toLowerCase() method returns the given string in lowercase letters.

<script>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
</script>

Output:
javascript tolowercase example
 JavaScript String toUpperCase() Method
The JavaScript String toUpperCase() method returns the given string in uppercase letters.

<script>
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
</script>

Output:
JAVASCRIPT TOUPPERCASE EXAMPLE

 JavaScript String slice(beginIndex, endIndex) Method


The JavaScript String slice(beginIndex, endIndex) method returns the parts of string from given beginIndex to endIndex. In slice() method, beginIndex is inclusive and
endIndex is exclusive.

<script>
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
</script>

Output:
cde
 JavaScript String trim() Method
The JavaScript String trim() method removes leading and trailing whitespaces from the string.

<script>
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
</script>

Output:
javascript trim

 JavaScript String split() Method

<script>
var str="This is JavaTpoint website";
document.write(str.split(" ")); //splits the given string.
</script>
 JavaScript Date Object
The JavaScript date object can be used to get year, month and day. You can display a timer on the webpage by the help of JavaScript date object. You can use different Date
constructors to create date object. It provides methods to get and set day, month, year, hour, minute and seconds.

 Constructor
You can use 4 variant of Date constructor to create date object.
o Date()
o Date(milliseconds)
o Date(dateString)
o Date(year, month, day, hours, minutes, seconds, milliseconds)

 JavaScript Date Example


Let's see the simple example to print date object. It prints date and time both.

Current Date and Time:


<span id="txt"></span>
<script>
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script>

Output:
Current Date and Time: Fri Mar 19 2021 12:48:42 GMT+0530 (India Standard Time)
Let's see another code to print date/month/year.

<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
</script>

Output:
Date is: 19/3/2021

 JavaScript Current Time Example


Let's see the simple example to print current time of system.

Current Time: <span id="txt"></span>


<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>

Output:
Current Time: 12:48:42
 JavaScript Boolean
JavaScript Boolean is an object that represents value in two states: true or false. You can create the JavaScript Boolean object by Boolean() constructor as given
below:
Boolean b=new Boolean(value);

The default value of JavaScript Boolean object is false.

 JavaScript Boolean Example

<script>
document.write(10<20); //true
document.write(10<5); //false
</script>

 JavaScript Boolean Properties

Property Description

constructor returns the reference of Boolean function that created Boolean object.

prototype enables you to add properties and methods in Boolean prototype.

 JavaScript Boolean Methods

Method Description

toSource() returns the source of Boolean object as a string.


toString() converts Boolean into String.

valueOf() converts other type into Boolean.

 Window Object
The Window object is the top level object in the JavaScript hierarchy. The Window object represents a browser window. A Window object is created
automatically with every instance of a <body> or <frameset> tag.
IE: Internet Explorer, F: Firefox, O: Opera.

 Collection Description
frames[] Returns all named frames in the window

 Window Object Properties


Property Description
closed Returns whether or not a window has been closed
defaultStatus Sets or returns the default text in the statusbar of the window
Document See Document object
history See History object
length Sets or returns the number of frames in the window
location See Location object
name Sets or returns the name of the window
opener Returns a reference to the window that created the window
outerHeight Sets or returns the outer height of a window
outerWidth Sets or returns the outer width of a window
pageXOffset Sets or returns the X position of the current page in relation to the upper left corner of a window's display
area.
pageYOffset Sets or returns the Y position of the current page in relation to the upper left corner of a window's display
area
parent Returns the parent window
personalbar Sets whether or not the browser's personal bar (or directories bar) should be visible.

scrollbars Sets whether or not the scrollbars should be visible


self Returns a reference to the current window
status Sets the text in the statusbar of a window
statusbar Sets whether or not the browser's statusbar should be visible

 Window Object Methods


Method Description
alert() Displays an alert box with a message and an OK button
blur() Removes focus from the current window
clearInterval() Cancels a timeout set with setInterval()
clearTimeout() Cancels a timeout set with setTimeout()
close() Closes the current window
confirm() Displays a dialog box with a message and an OK and a Cancel button
createPopup() Creates a pop-up window
focus() Sets focus to the current window
moveBy() Moves a window relative to its current position
moveTo() Moves a window to the specified position
open() Opens a new browser window
print() Prints the contents of the current window
prompt() Displays a dialog box that prompts the user for input
resizeBy() Resizes a window by the specified pixels
resizeTo() Resizes a window to the specified width and height
scrollBy() Scrolls the content by the specified number of pixels
scrollTo() Scrolls the content to the specified coordinates
setInterval() Evaluates an expression at specified intervals
setTimeout() Evaluates an expression after a specified number of milliseconds
 Document Object
The Document object represents the entire HTML document and can be used to access all elements in a page. The Document object is part of the Window
object and is accessed through the window.document property.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard).

 Document Object Collections


Collection Description
anchors[] Returns a reference to all Anchor objects in the document
forms[] Returns a reference to all Form objects in the document
images[] Returns a reference to all Image objects in the document
links[] Returns a reference to all Area and Link objects in the document

 Document Object Properties


Property Description
body Gives direct access to the <body> element
Cookie Sets or returns all cookies associated with the current document
domain Returns the domain name for the current document
lastModified Returns the date and time a document was last modified
referrer Returns the URL of the document that loaded the current document
title Returns the title of the current document
URL Returns the URL of the current document

 Document Object Methods


Method Description
close() Closes an output stream opened with the document.open() method, and displays the collected data
getElementById() Returns a reference to the first object with the specified id
getElementsByName() Returns a collection of objects with the specified name
getElementsByTagName() Returns a collection of objects with the specified tagname
open() Opens a stream to collect the output from any document.write() or document.writeln() methods
write() Writes HTML expressions or JavaScript code to a document
writeln() Identical to the write() method, with the addition of writing a new line character after each expression

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy