Created
December 9, 2015 16:59
-
-
Save khzaw/df5468ebfa0689267cc0 to your computer and use it in GitHub Desktop.
Javascript class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// the class use | |
class Animal { | |
constructor(name) { | |
this.name = name; | |
} | |
walk() { | |
console.log(`${this.name} is walking`); | |
} | |
} | |
// Kyle Simpson's OLOO style | |
// Using ES6's shorthand for functions | |
let Animal = { | |
init(name) { | |
this.name = name; | |
return this; | |
} | |
walk() { | |
console.log(`${this.name} is walking`); | |
} | |
}; | |
// fat arrow | |
let Animal = { | |
init: (name) => { | |
this.name = name; | |
return this; | |
}, | |
walk: () => { | |
console.log(this.name + " is walking"); | |
} | |
}; | |
// less es6-y | |
var Animal = { | |
init: function(name) { | |
this.name = name; | |
return this; | |
}, | |
walk: function() { | |
console.log(this.name + " is walking"); | |
} | |
}; | |
// Without using the this keyword | |
// Using closure | |
var Animal = (function(name) { | |
var self = {}; | |
self.name = name || ""; | |
self.walk = function() { | |
return "Walked"; | |
}; | |
return self; | |
}); | |
// Strictly closures, Douglas Crockford way | |
function Animal(spec) { | |
let {name} = spec; | |
let walk = () => { | |
console.log(`${name} is walking`); | |
}; | |
return Object.freeze({ | |
walk | |
}); | |
} | |
function Animal({name} = {}) { | |
let walk = () => { | |
console.log(`${name} is walking`); | |
}; | |
return Object.freeze({ | |
walk | |
}); | |
} | |
// the generic Constructor function pattern | |
function Animal(name) { | |
this.name = name; | |
}; | |
Animal.prototype.walk = function() { | |
console.log(this.name + " is walking"); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment