Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 2nd, 2012  |  syntax: None  |  size: 1.10 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. var person = Object.make(null, {
  2.   get name() {
  3.     return this.first_name + " " + this.last_name;
  4.   },
  5.   set name() {
  6.     ...
  7.   },
  8.   greet: function (person) {
  9.     return this.name + ': Why, hello there, ' + person + '.'
  10.   }
  11. })
  12.  
  13. // Then we can share those behaviours with Mikhail
  14. // By creating a new object that has it's [[Prototype]] property
  15. // pointing to `person'.
  16. var mikhail = Object.make(person, {
  17.   first_name: 'Mikhail',
  18.   last_name: 'Weiß',
  19.   age: 19,
  20.   gender: 'Male'
  21. })
  22.  
  23. // And we can test whether things are actually working.
  24. // First, `name' should be looked on `person'
  25. mikhail.name
  26. // => 'Mikhail Weiß'
  27.  
  28. // Setting `name' should trigger the setter
  29. mikhail.name = 'Michael White'
  30.  
  31. // Such that `first_name' and `last_name' now reflect the
  32. // previously name setting.
  33. mikhail.first_name
  34. // => 'Michael'
  35. mikhail.last_name
  36. // => 'White'
  37.  
  38. // `greet' is also inherited from `person'.
  39. mikhail.greet('you')
  40. // => 'Michael White: Why, hello there, you.'
  41.  
  42. // And just to be sure, we can check which properties actually
  43. // belong to `mikhail'
  44. Object.keys(mikhail)
  45. // => [ 'first_name', 'last_name', 'age', 'gender' ]