An object in JavaScript is a self-contained entity having attributes and a type. Consider a cup as an example. A cup is a physical item having qualities. A cup has a color, a pattern, a weight, a material made of, and so on. JavaScript objects, too, may have attributes that determine their qualities.
JavaScript variables, as you well know, are containers for data values.
This code gives a basic value (Fiat) to the variable car:
EXAMPLE
HTML
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p id="demo"></p>
</body>
</html>
JAVASCRIPT
// Create and display a variable:
let car = "Suzuki";
document.getElementById("demo").innerHTML = car;
Objects are also variables. However, objects can have several values.
This code assigns many values (Fiat, 500, white) to the variable car:
EXAMPLE
HTML
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p id="demo"></p>
</body>
</html>
JAVASCRIPT
// Create an object:
const car = {type:"Suzuki", model:"420", color:"black"};
// Display some data from the object:
document.getElementById("demo").innerHTML = "The car type is " + car.type;
An object literal is used to define (and construct) a JavaScript object:
EXAMPLE
HTML
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p id="demo"></p>
</body>
</html>
JAVASCRIPT
// Create an object:
const person = {firstName:"Gideon", lastName:"Arias", age:18, eyeColor:"Black"};
// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
You can access object properties in two ways:
EXAMPLE
HTML
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>HOWDYYYY! It's me again partner! I'll explain how this works<p>
<p>(Coughs) As you can see, there are two methods for accessing an object attribute.</p>
<p>You can use person.property or person["property"].</p>
<p>Let me use my friend here again cause why not? ;)</p>
<p id="demo"></p>
</body>
</html>
JAVASCRIPT
const person = {
firstName: "Gideon",
lastName : "Arias",
Student : "MAWD 403",
id : 2000248085
};
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
This refers to the object in an object method. This refers to the global object on its own. This refers to the global object in a function. This is undefined in a function in strict mode. This refers to the element that got the event in an event.
EXAMPLE
HTML
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>Howdy! It's me again your favorate partner! Just kidding HAHAHAHA</p>
<p>Alrighty, I'll explain how this works. You see a function definition is kept as a property value in an object method.</p>
<p>I'll use my favorate friend over here again ;)</p>
<p id="demo"></p>
</body>
</html>
JAVASCRIPT
const person = {
firstName: "Gideon",
lastName: "Arias",
Student : "MAWD 403",
id: 2000248085,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
document.getElementById("demo").innerHTML = person.fullName();