javaScriptlesson9
javaScriptlesson9
To display an object in JavaScript, we commonly use console.log(). When you log an object to the
console, it is shown in a structured format where you can expand and collapse the properties for better
readability.
In more complex scenarios, you can iterate over the object to display its properties and values. There are
several methods you can use to display object properties:
javascript
Copy code
2. Constructor Functions
A constructor function is a special type of function that is used to create and initialize objects in
JavaScript. It is a template for creating objects with the same properties and methods.
We define a Person constructor function with three properties: name, age, and profession.
You can also add methods to constructor functions. However, methods should not be added directly
inside the constructor function. Instead, they should be added to the prototype of the constructor
function.
In this case, the method greet() is added to the Person prototype. All instances of Person will have access
to this method.
The new keyword is crucial when using constructor functions. It does several things:
4. Returns the new object, unless you explicitly return something else in the constructor.
For example:
In JavaScript, objects created with constructors have an internal link to their constructor's prototype.
This is how inheritance works in JavaScript.
You can add methods to an object's prototype to allow all instances of that object to share the same
method.
In this example, the speak() method is shared across all instances of Animal.
You can also extend classes and create subclasses in JavaScript using extends and super.
Summary
Displaying Objects: Use console.log(), Object.keys(), Object.values(), or Object.entries() to
display and iterate over object properties.
Constructor Functions: Use a function with the new keyword to create new objects.
Adding Methods: Methods can be added to the object's prototype, or directly within the
constructor (or class).
Using ES6 Classes: ES6 introduces classes, which provide a cleaner syntax for creating objects
and methods.