Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
94 views

Java Script Object

The document provides information on JavaScript objects including: 1) Objects store keyed collections of data and properties and can be created using object literals with curly braces. 2) Properties are "key: value" pairs within an object where the key is a string and the value can be any data type. 3) Objects can have methods which are functions stored as object properties and accessed using dot notation. 4) The this keyword in methods refers to the object the method is called on. 5) Constructor functions can be used to create object types and the new keyword instantiates objects from constructors. 6) Prototype inheritance allows objects to inherit properties and methods from constructors.

Uploaded by

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

Java Script Object

The document provides information on JavaScript objects including: 1) Objects store keyed collections of data and properties and can be created using object literals with curly braces. 2) Properties are "key: value" pairs within an object where the key is a string and the value can be any data type. 3) Objects can have methods which are functions stored as object properties and accessed using dot notation. 4) The this keyword in methods refers to the object the method is called on. 5) Constructor functions can be used to create object types and the new keyword instantiates objects from constructors. 6) Prototype inheritance allows objects to inherit properties and methods from constructors.

Uploaded by

Nida khan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Web Design Concept

07-10-2020
Objects
Objects are used to store keyed collections of various data and more
complex entities. In JavaScript, objects penetrate almost every aspect
of the language.
An object can be created with figure brackets {…} with an optional list
of properties. A property is a “key: value” pair, where key is a string
(also called a “property name”), and value can be anything.
An empty object (“empty cabinet”) can be created using one of two
syntaxes:

let user = new Object(); // "object constructor" syntax


let user = {}; // "object literal" syntax

Usually, the figure brackets {...} are used. That declaration is called an
object literal.
Literals and properties
We can immediately put some properties into {...} as “key: value” pairs:

let user = { // an object


name: "John", // by key "name" store value "John"
age: 30 // by key "age" store value 30
};

A property has a key (also known as “name” or “identifier”) before the colon ":" and a value to the right of it.

In the user object, there are two properties:

The first property has the name "name" and the value "John".
The second one has the name "age" and the value 30.
We can add, remove and read files from it any time.

Property values are accessible using the dot notation:

// get property values of the object:


alert( user.name ); // John
alert( user.age ); // 30
We can also use multiword property names, but then they must be
quoted:

let user = {
name: "John",
age: 30,
"likes birds": true // multiword property name must be quoted
};
The last property in the list may end with a comma:

let user = {
name: "John",
age: 30,
}
Object with const can be changed
Please note: an object declared as const can be modified.
For instance:
const user = {
name: "John"
};
user.name = "Pete"; // (*)
alert(user.name); // Pete
It might seem that the line (*) would cause an error, but no. The const
fixes the value of user, but not its contents.
The const would give an error only if we try to set user=... as a whole.
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"}

var x = person;
x.age = 10;

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
var person = new Object();
person.firstName = “Nida";
person.lastName = “Khan";
person.age = 23;
person.eyeColor = “Red";

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
JavaScript Properties
Properties are the values associated with a JavaScript 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 // person.age
or

objectName["property"] // person["age"]
or

objectName[expression] // x = "age"; person[x]


<p>There are two different ways to access an object property:</p>
<p>You can use .property or ["property"].</p>

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

<script>
let person = {
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};

document.getElementById("demo").innerHTML = person.firstname + " is " + person.age + " years


old.";
<h2>JavaScript Object Properties</h2>
<p>There are two different ways to access an object property:</p>
<p>You can use .property or ["property"].</p>

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

<script>
let person = {
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};
document.getElementById("demo").innerHTML = person["firstname"] + " is " + person["age"] + "
years old.";
The “for…in” loop
To walk over all keys of an object, there exists a special form of the
loop: for..in. This is a completely different thing from the for(;;)
construct.

The syntax:

for (key in object) {


// executes the body for each key among object properties
}
For instance, let’s output all properties of
user:
let user = {
name: "John",
age: 30,
isAdmin: true
};

for (let key in user) {


// keys
alert( key ); // name, age, isAdmin
// values for the keys
alert( user[key] ); // John, 30, true
}
Ordered like an object
“ordered in a special fashion”: integer properties are sorted, others appear in creation order. The details
follow.
let codes = {
"49": "Germany",
"41": "Switzerland",
"44": "Great Britain",
// ..,
"1": "USA"
};

for (let code in codes) {


alert(code); // 1, 41, 44, 49
}
if the keys are non-integer, then they are listed in the creation order, for
instance:
let user = {
name: "John",
surname: "Smith"
};
user.age = 25; // add one more

// non-integer properties are listed in the creation order


for (let prop in user) {
alert( prop ); // name, surname, age
}
To fix the issue with the phone codes, we can “cheat” by making the codes non-integer.
Adding a plus "+" sign before each code is enough.

let codes = {
"+49": "Germany",
"+41": "Switzerland",
"+44": "Great Britain",
// ..,
"+1": "USA"
};

for (let code in codes) {


alert( +code ); // 49, 41, 44, 1
}
• Adding New Properties
You can add new properties to an existing object by simply giving it a value.
Assume that the person object already exists - you can then give it new properties:
<p id="demo"></p>
<script>
Let person = {
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};

person.nationality = "English";
document.getElementById("demo").innerHTML =
person.firstname + " is " + person.nationality + ".";
Deleting Properties
<p id="demo"></p>

<script>
var person = {
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};

delete person.age;
document.getElementById("demo").innerHTML =
person.firstname + " is " + person.age + " years old.";
</script>
The this Keyword

In a function definition, this refers to the "owner" of the function.

JAVASCRIPT METHOD

JavaScript methods are actions that can be performed on objects.


A JavaScript method is a property containing a function definition.
Methods are functions stored as object properties.
<p id="demo"></p>

<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

// Display data from the object:


document.getElementById("demo").innerHTML = person.fullName();
</script>
Accessing Object Methods
You access an object method with the following syntax:
objectName.methodName()
JavaScript Display Objects
<p id="demo"></p>

<script>
let person = {name:"John", age:30, city:"New York"};

document.getElementById("demo").innerHTML = person;
</script>
• Some common solutions to display JavaScript objects are:

• Displaying the Object Properties by name


• Displaying the Object Properties in a Loop
• Displaying the Object using Object.values()
• Displaying the Object using JSON.stringify()
<p id="demo"></p>
<script>
var person = {name:"John", age:50, city:"New York"};

document.getElementById("demo").innerHTML = person.name + "," +


person.age + "," + person.city;
</script>

</body>
</html>
Using Object.values()
<p id="demo"></p>
<script>
var person = {name:"John", age:50, city:"New York"};
var myArray = Object.values(person);
document.getElementById("demo").innerHTML = myArray;
</script>
Using JSON.stringify()
Any JavaScript object can be stringified (converted to a string) with the
JavaScript function JSON.stringify():

<p id="demo"></p>
<script>
var person = {name:"John", age:50, city:"New York"};
var myString = JSON.stringify(person);
document.getElementById("demo").innerHTML = myString;
Stringify Dates
JSON.stringify converts dates into strings:

var person = {name:"John", today:new Date()};

var myString = JSON.stringify(person);
document.getElementById("demo").innerHTML = myString;
Stringify Arrays
It is also possible to stringify JavaScript arrays:

var arr = ["John", "Peter", "Sally", "Jane"];

var myString = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myString;
JavaScript Object Constructors
The examples from the previous chapters are limited. They only create
single objects.
Sometimes we need a "blueprint" for creating many objects of the same
"type".
The way to create an "object type", is to use an object constructor
function.
In the example above, function Person() is an object constructor
function.
Objects of the same type are created by calling the constructor function
with the new keyword:
<p id="demo"></p>
<script>
// Constructor function for Person objects
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
// Create two Person objects
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
// Display age
document.getElementById("demo").innerHTML =
"My father is " + myFather.age + ". My mother is " + myMother.age + ".";
</script>
Adding a Method to a Constructor
<p id="demo"></p>
<script>
// Constructor function for Person objects
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
this.name = function() {
return this.firstName + " " + this.lastName
};
}
// Create a Person object
var myFather = new Person("John", "Doe", 50, "blue");
// Display full name
document.getElementById("demo").innerHTML =
"My father is " + myFather.name();
JavaScript Object Prototypes
Prototype Inheritance
All JavaScript objects inherit properties and methods from a prototype:

Date objects inherit from Date.prototype


Array objects inherit from Array.prototype
Person objects inherit from Person.prototype
The Object.prototype is on the top of the prototype inheritance chain:

Date objects, Array objects, and Person objects inherit from


Object.prototype.
Using the prototype Property
The JavaScript prototype property allows you to add new properties to object constructors:
<p id="demo"></p>

<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype.nationality = "English";
var myFather = new Person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"The nationality of my father is " + myFather.nationality;
</script>
The JavaScript prototype property also allows you to add new methods to objects constructors:
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName
};
var myFather = new Person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"My father is " + myFather.name();
</script>
Java Script Form

• Form validation normally used to occur at the server, after the client had entered all the necessary data and then pressed the
Submit button. If the data entered by a client was incorrect or was simply missing, the server would have to send all the data
back to the client and request that the form be resubmitted with correct information. This was really a lengthy process which
used to put a lot of burden on the server.
• JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Form validation
generally performs two functions.
• Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require
just a loop through each field in the form and check for data.
• Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must
include appropriate logic to test correctness of data.
• Example
<html><body><script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form> </body></html>
JavaScript Retype Password Validation
<script type="text/javascript">  
function matchpass(){  
var firstpassword=document.f1.password.value;  
var secondpassword=document.f1.password2.value;  
  
if(firstpassword==secondpassword){  
return true;  
}  
else{  
alert("password must be same!");  
return false;  
}  
}  
</script>  
 <form name="f1" action="register.jsp" onsubmit="return matchpass()">  
Password:<input type="password" name="password" /><br/>  
Re-enter Password:<input type="password" name="password2"/><br/>  
<input type="submit">  
</form>  

You might also like