ES6 -Working with Objects Reply

Rick HerrmannWant to work with the Nerdia team? Submit your resume.

Today we are looking at several new ES6 features that make working with objects easier.

Object.assign

The new assign function is used to copy all of the properties from one (or more) object(s) to another object.  I have used this feature many times before in other libraries (jquery, underscore, lodash, angular) – always in the form of an extend function.  The syntax looks like the following, where all of the properties in the source objects are copied to the target object:

Object.assign(target, ...sources)

 

let person = {
  name: 'Lumberg'
};
let employee = {
  title: 'Manager'
};
let actions = {
  speak: () => 'umm yeah'
}
Object.assign(person, employee, actions);
expect(person.title).toBe('Manager');
expect(person.speak()).toBe('umm yeah');

 

Property Initializers

Both the property and method initializers for initializing an object can be written more tersely than in ES5. For properties, the property name can be inferred from a variable. For example:

let city = 'Detroit';
let team = 'Tigers';

let baseballTeam = {
  city,
  team,
};
expect(baseballTeam.city).toBe('Detroit');
expect(baseballTeam.team).toBe('Tigers');

Method initialization can also be shortened to:

let thermometer = {
  getTemperature() {
    return 20;
  }
};

expect(thermometer.getTemperature()).toBe(20);

Proxies

Proxies allow you to intercept calls on an object. This could be a getter or setter on a property, or a function call. The proxy does not replace the functionality of the object, but instead creates a wrapper around the object that has custom behavior. Proxies can be useful for adding validation, enhancing a third party library, testing, or adding property modified event notifications. Here is an example of creating a proxy for a property setter:

let car = {
            year: 2015,
            make: 'Ford',
            price: 20000
        };
let carProxy = new Proxy(car, {
            set: (target, property, value) => {
                if (property === 'price') {
                    console.log('price was changed');
                   //trigger an event to notify that the price has changed
                }
                target[property] = value;
            }
        });

carProxy.price = 19000;  //should raise an event;

Functions can also be wrapped:

let car = {
  year: 2015,
  make: 'Ford',
  price: 20000,
  drive: (person) => {
    return person.name + ' is driving';
  }
};
car.drive = new Proxy(car.drive, {
  apply: (target, context, args) => {
    if(args[0].age > 16) {
      return args[0].name + 'is too young to drive';
    } else {
      return target.apply(context, args);
    }
  }
}
let person = {name:'bart', age:10};
expect(car.drive(bart)).toBe('bart is too young to drive');

Notice that in the case of the drive function, the entire car object is not wrapped, just the function.

The new object and proxy functionality make working with objects more efficient and powerful with ES6.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s