Barth Zalewski Barth Zalewski - 23 days ago 18
Javascript Question

Arrow function in object definition

In Javascript Harmony, we can for example do the following:

var maths = {
sum (...args) {
let r = 0;
for (let num of args) {
r += num;
}
return r;
}
};
maths.sqr = n => n * n;


I just wondered if there is any way to use an arrow function, like
sqr
within the object definition, just like
sum
.

Answer

You could just write it as literal.

var maths = {
        sqr: n => n * n,
        sum (...args) {
            let r = 0;
            for (let num of args) {
                r += num;
            }
            return r;
        }
    };

console.log(maths.sqr(5));
console.log(maths.sum(2, 4, 5));

Comments