Skip to content

Instantly share code, notes, and snippets.

@ivan-ha
Last active April 5, 2017 13:38
Show Gist options
  • Select an option

  • Save ivan-ha/cbefaf2c47f76c30ce5fb949d0360b9a to your computer and use it in GitHub Desktop.

Select an option

Save ivan-ha/cbefaf2c47f76c30ce5fb949d0360b9a to your computer and use it in GitHub Desktop.
JS delegation
/**
* Simulate classical ineritance (not recommended) using constructor function
*/
function Greeter (name) {
this.name = name || 'John Doe';
}
Greeter.prototype.hello = function hello () {
return 'Hello, my name is ' + this.name;
}
var george = new Greeter('George');
var msg = george.hello();
console.log(msg); // Hello, my name is George
/**
* Classical ineritance, not recommended
*/
class Greeter {
constructor (name) {
this.name = name || 'John Doe';
}
hello () {
return `Hello, my name is ${ this.name }`;
}
}
const george = new Greeter('George');
const msg = george.hello();
console.log(msg); // Hello, my name is George
const proto = {
hello () {
return `Hello, my name is ${ this.name }`;
}
};
const greeter = (name) => Object.assign(Object.create(proto), {
name
});
const george = greeter('george');
const msg = george.hello();
console.log(msg);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment