JS-7
JS-7
1. Object Literal:
javascript
Copy code
const person = {
name: 'John',
age: 30,
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
2. Constructor Function:
javascript
Copy code
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
}
const john = new Person('John', 30);
3. Object.create():
javascript
Copy code
const personPrototype = {
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
const john = Object.create(personPrototype);
john.name = 'John';
john.age = 30;
Object prototype methods are methods that are defined on the prototype object of an object
constructor. These methods are shared among all instances of the constructor function and
can be accessed using dot notation.
Example:
javascript
Copy code
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const john = new Person('John');
john.greet(); // Output: Hello, my name is John
Object chaining is a technique where multiple methods or properties are accessed in a chain-
like manner on an object. It improves code readability and reduces the need for temporary
variables.
Example:
javascript
Copy code
const calculator = {
value: 0,
add(num) {
this.value += num;
return this;
},
subtract(num) {
this.value -= num;
return this;
},
multiply(num) {
this.value *= num;
return this;
},
getValue() {
return this.value;
}
};
Question 4: Main Difference between Fat Arrow Function and Normal Function:
Example to Explain "this" with Fat Arrow Function and Normal Function:
javascript
Copy code
const obj = {
name: 'John',
normalFunc: function() {
console.log(this.name); // Output: John
},
arrowFunc: () => {
console.log(this.name); // Output: undefined (lexical this)
}
};
• Simpler API: Axios provides a cleaner and easier-to-use API compared to fetch and
other competitors.
• Automatic JSON Parsing: Axios automatically parses JSON responses, reducing
manual parsing.
• Interceptors: Axios allows intercepting and transforming requests and responses.
• Browser Compatibility: Axios supports older browsers and has better cross-browser
compatibility.
• Error Handling: Axios has built-in error handling and response validation features.
• Cancellation: Axios supports cancellation of requests, which can be useful in certain
scenarios.
A closure is a function defined inside another function (outer function) and has access to
variables declared in the outer function, even after the outer function has finished executing.
Example:
javascript
Copy code
function outerFunction() {
const message = 'Hello';
function innerFunction() {
console.log(message);
}
return innerFunction;
}
In this example, innerFunction is a closure that retains access to the message variable of
outerFunction, even though outerFunction has finished executing.