Java Script Object
Java Script Object
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:
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:
A property has a key (also known as “name” or “identifier”) before the colon ":" and a value to the right of it.
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.
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
<p id="demo"></p>
<script>
let person = {
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};
<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:
let codes = {
"+49": "Germany",
"+41": "Switzerland",
"+44": "Great Britain",
// ..,
"+1": "USA"
};
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
JAVASCRIPT METHOD
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
<script>
let person = {name:"John", age:30, city:"New York"};
document.getElementById("demo").innerHTML = person;
</script>
• Some common solutions to display JavaScript objects are:
</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 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:
<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>