parent
1b639c433c
commit
1dd53d8994
3 changed files with 66 additions and 0 deletions
@ -0,0 +1,27 @@ |
|||||||
|
The prototype chain in JavaScript refers to the chain of objects linked by their prototypes. When a property or method is accessed on an object, JavaScript first checks the object itself. If it doesn't find it there, it looks up the property or method in the object's prototype. This process continues, moving up the chain from one prototype to the next, until the property or method is found or the end of the chain is reached (typically the prototype of the base object, which is `null`). The prototype chain is fundamental to JavaScript's prototypal inheritance model, allowing objects to inherit properties and methods from other objects. |
||||||
|
|
||||||
|
## Example |
||||||
|
|
||||||
|
```js |
||||||
|
const roadmap = { |
||||||
|
getRoadmapUrl() { |
||||||
|
console.log(`https://roadmap.sh/${this.slug}`); |
||||||
|
}, |
||||||
|
}; |
||||||
|
|
||||||
|
const javascript = { |
||||||
|
name: 'JavaScript Roadmap', |
||||||
|
description: 'Learn JavaScript', |
||||||
|
slug: 'javascript', |
||||||
|
greet() { |
||||||
|
console.log(`${this.name} - ${this.description}`); |
||||||
|
}, |
||||||
|
}; |
||||||
|
|
||||||
|
Object.setPrototypeOf(javascript, roadmap); // or javascript.__proto__ = roadmap; |
||||||
|
|
||||||
|
javascript.getRoadmapUrl(); // https://roadmap.sh/javascript |
||||||
|
javascript.greet(); // JavaScript Roadmap - Learn JavaScript |
||||||
|
``` |
||||||
|
|
||||||
|
In the above example, the `javascript` object inherits the `getRoadmapUrl()` method from the `roadmap` object. This is because the `javascript` object's prototype is set to the `roadmap` object using the `Object.setPrototypeOf()` method. In the `javascript` object, the `getRoadmapUrl()` method is not found, so JavaScript looks up the prototype chain and finds the `getRoadmapUrl()` method in the `roadmap` object. |
@ -0,0 +1,24 @@ |
|||||||
|
You can use the `reduce()` method to reduce an array to a single value. The `reduce()` method executes a reducer function (that you provide) on each element of the array, resulting in a single output value. |
||||||
|
|
||||||
|
## Syntax |
||||||
|
|
||||||
|
```js |
||||||
|
array.reduce((accumulator, currentValue) => { |
||||||
|
// ... |
||||||
|
}, initialValue); |
||||||
|
``` |
||||||
|
|
||||||
|
## Example |
||||||
|
|
||||||
|
You can use the `reduce()` method to sum all the numbers in an array. |
||||||
|
|
||||||
|
```js |
||||||
|
const numbers = [1, 2, 3, 4, 5, 6]; |
||||||
|
|
||||||
|
const sum = numbers.reduce((accumulator, currentValue) => { |
||||||
|
return accumulator + currentValue; |
||||||
|
}, 0); |
||||||
|
|
||||||
|
console.log(numbers); // [1, 2, 3, 4, 5, 6] |
||||||
|
console.log(sum); // 21 |
||||||
|
``` |
Loading…
Reference in new issue