Let's add a function to the object that will perform some useful operation. For example, it will find the sum of the object elements.
Let's have an object:
let obj = {a: 1, b: 2, c: 3};
Let's create a symbol:
let sym = Symbol();
And write a function:
obj[sym] = function() {
};
In a function bound to an object,
this
will refer to the
object itself:
obj[sym] = function() {
console.log(this); // {a: 1, b: 2, c: 3}
};
Using our function, we will find the sum of the object elements:
obj[sym] = function() {
let sum = 0;
for (let key in this) {
sum += this[key];
}
return sum;
};
Let's invoke our function, getting the sum of the object elements:
let sum = obj[sym]();
console.log(sum); // shows 6
Given an array:
let arr = [1, 2, 3];
In the way described in the lesson, add a function to the array that will return the sum of the array elements.
Call the function you created and make sure it finds the sum correctly.
Add several elements to the array
using the push
method. Make
sure the function will find the sum
given the new elements.