JavaScript objects creation using method


#1

let person = {
name: ‘Tyron’,
age: 40 ,
weekendAlarm : ‘No alarms needed’ ,
weekAlarm : ‘Alarm set to 7AM’,

sayHello : () => {
return ‘Hello, there!’;
}
};
In this example we are creating the person object with 5 keys including one method named sayHello().
My query :
Can a method definition can be added to the person object later in the code?
Meaning javascript provides functionality to edit and add a normal key value pair to an existing object later after its 1st declaration but does it allow to add the new key with method as its value ?
I was trying :
let person = {
name: ‘Tyron’,
age: 40 ,
weekendAlarm : ‘No alarms needed’ ,
weekAlarm : ‘Alarm set to 7AM’
};
person.sayHello = () => { return ‘Hello, there!’;};

But this is throwing error unexpected token =>


#2

Yes, by declaring a new attribute name and setting it to the method.

person.newMethod = function (args) {
    // method code has `this` in scope
};

Now query the object for hasOwnProperty

 > person.hasOwnProperty('newMethod')
<- true

It will take a little reading but arrow functions may not be allowed in that context. Possibly it might be the {}'s and the return keyword.

person.sayHello = () => "Hello, there!";

If this is still an issue then revert to the ES5 function syntax in the example above.


Looking at this further… Object methods are not allowed to use arrow function syntax.

However, there is a relaxed syntax for methods…

person = {

    sayHello () {

    }
};

Also something else to read up on.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.