1

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.

4
  • Yes you can do, But the this value will differ, It will not point to the maths object. Commented Nov 10, 2016 at 12:53
  • Can you provide syntax for this, please? Commented Nov 10, 2016 at 12:54
  • var maths = { sqr : n => n * n; }; Here you go. Commented Nov 10, 2016 at 12:55
  • Nice, thanks. That would be the accepted answer. Commented Nov 10, 2016 at 12:57

1 Answer 1

3

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));

Sign up to request clarification or add additional context in comments.

2 Comments

My sum is not wrong, it just uses another syntax. I wondered if we can use the same syntax without :, but apparently not, as your example shows.
i have never seen this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.