Unit 2-3 - Web Technology
Unit 2-3 - Web Technology
B.Tech – V Semester
UNIT II
M. Vijayakumar
Assistant Professor (SS)
School of Computing Sciences,
Department of Computer Science and Engineering
JavaScript Objects
A car has properties like weight and color, and methods like start and stop:
Properties Methods
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
<h2>JavaScript Variables</h2>
<p id="demo"></p>
<script>
// Create and display a variable:
let car = "Fiat";
document.getElementById("demo").innerHTML = car;
</script>
</body>
</html>
Department of Computer science and Engineering CSB4301 - WEB TECHNOLOGY 4
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};
</body>
</html>
Department of Computer science and Engineering CSB4301 - WEB TECHNOLOGY 5
The values are written as name:value pairs (name and value separated by a colon).
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
</body>
</html>
Department of Computer science and Engineering CSB4301 - WEB TECHNOLOGY 8
Object Properties
The name:values pairs in JavaScript objects are called properties:
objectName.propertyName
or
objectName["propertyName"]
<h2>JavaScript Objects</h2>
In the example above, this is the person object that "owns" the fullName function.
objectName.methodName()
</body>
</html>
Department of Computer science and Engineering CSB4301 - WEB TECHNOLOGY 16
If you access a method without the () parentheses, it will return the function definition:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>If you access an object method without (), it will return the function definition:</p>
<p id="demo"></p>
<script>
// Create an object:
const 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>
</body>
</html> Department of Computer science and Engineering CSB4301 - WEB TECHNOLOGY 17
Do Not Declare Strings, Numbers, and Booleans as Objects!
When a JavaScript variable is declared with the keyword "new", the variable is created
as an object:
x = new String(); // Declares x as a String object
y = new Number(); // Declares y as a Number object
z = new Boolean(); // Declares z as a Boolean object
Avoid String, Number, and Boolean objects. They complicate your code and slow down
execution speed.