Skip to content

Instantly share code, notes, and snippets.

@carlozamagni
Created October 5, 2016 06:24
Show Gist options
  • Save carlozamagni/c7bf630b9b98ca7b464cc8954417a053 to your computer and use it in GitHub Desktop.
Save carlozamagni/c7bf630b9b98ca7b464cc8954417a053 to your computer and use it in GitHub Desktop.
JavaScript class styles (from https://gist.github.com/tcrosen)
class Person {
constructor(props) {
this.firstName = props.firstName || 'John';
this.lastName = props.lastName || 'Doe';
}
getFullName() {
return this.firstName + ' ' + this.lastName;
}
}
console.log(new Person().getFullName()); // John Doe
class Person {
constructor({ firstName, lastName }) {
this.firstName = firstName || 'John';
this.lastName = lastName || 'Doe';
}
getFullName() {
return this.firstName + ' ' + this.lastName;
}
}
console.log(new Person({}).getFullName());
console.log(new Person({ lastName: 'Smith' }).getFullName()); // John Smith
/*
* -----------------------------------
* ALTERNATIVE WITH DEFAULT PARAMETERS
* -----------------------------------
*/
class Person {
constructor({ firstName = 'John', lastName = 'Doe' }) {
this.firstName = firstName;
this.lastName = lastName;
}
getFullName() {
return this.firstName + ' ' + this.lastName;
}
}
console.log(new Person({}).getFullName()); // John Doe
console.log(new Person({ lastName: 'Smith' }).getFullName()); // John Smith
// Destructuring alternative
constructor(props = {}) {
const { firstName = 'John', lastName = 'Doe' } = props;
this.firstName = firstName;
this.lastName = lastName;
}
// Destructuring alternative
constructor(props) {
const { firstName = 'John', lastName = 'Doe' } = props || {};
this.firstName = firstName;
this.lastName = lastName;
}
// Using Object.assign() (or _.assign)
constructor(props) {
const defaults = {
firstName: 'John',
lastName: 'Doe'
};
Object.assign(this, defaults, props);
}
function Person(props) {
this.firstName = props.firstName;
this.lastName = props.lastName;
}
Person.prototype.getFullName = function() {
return this.firstName + ' ' + this.lastName;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment