Guest User

Untitled

a guest
Dec 12th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. // the class definition
  2. const $class = {
  3. hello() {
  4. console.log(`hello, my name is ${this.name}`);
  5. },
  6. };
  7.  
  8. // this function will create new $class instances
  9. function createClass(name) {
  10. const instance = {
  11. name,
  12. };
  13.  
  14. return Object.setPrototypeOf(instance, $class);
  15. }
  16.  
  17. // we don't line newing things, as it's not necesary
  18. // but if you do, do it from inside a factory function
  19. // eg. (data) => new Class(data)
  20. // that way, your code is cleaner, SOLID and everybody is happy!
  21. const annie = createClass("annie");
  22. const jack = createClass("jack");
  23.  
  24. annie.hello();
  25. jack.hello();
  26.  
  27. console.log(`are annie and jack the same object?`, annie === jack); // false, two different objects
  28.  
  29. console.log(`is any insance of class?`, annie instanceof createClass); // false, because we don't use the new operator
  30.  
  31. // true, good!
  32. console.log(
  33. `is jack's prototype $class?`,
  34. Object.getPrototypeOf(jack) === $class,
  35. );
  36.  
  37. // true, awesome!!
  38. console.log(
  39. `do annie and jack prototype is the same?`,
  40. Object.getPrototypeOf(annie) === Object.getPrototypeOf(jack),
  41. );
Add Comment
Please, Sign In to add comment