Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created November 19, 2011 16:59
Show Gist options
  • Save Raynos/1379051 to your computer and use it in GitHub Desktop.
Save Raynos/1379051 to your computer and use it in GitHub Desktop.
var person = Object.make(null, {
get name() {
return this.first_name + " " + this.last_name;
},
set name() {
...
},
greet: function (person) {
return this.name + ': Why, hello there, ' + person + '.'
}
})
// Then we can share those behaviours with Mikhail
// By creating a new object that has it's [[Prototype]] property
// pointing to `person'.
var mikhail = Object.make(person, {
first_name: 'Mikhail',
last_name: 'Weiß',
age: 19,
gender: 'Male'
})
// And we can test whether things are actually working.
// First, `name' should be looked on `person'
mikhail.name
// => 'Mikhail Weiß'
// Setting `name' should trigger the setter
mikhail.name = 'Michael White'
// Such that `first_name' and `last_name' now reflect the
// previously name setting.
mikhail.first_name
// => 'Michael'
mikhail.last_name
// => 'White'
// `greet' is also inherited from `person'.
mikhail.greet('you')
// => 'Michael White: Why, hello there, you.'
// And just to be sure, we can check which properties actually
// belong to `mikhail'
Object.keys(mikhail)
// => [ 'first_name', 'last_name', 'age', 'gender' ]
var person = Object.create(null)
// Here we are reusing the previous getter/setter functions
Object.defineProperty(person, 'name', { get: get_full_name
, set: set_full_name
, configurable: true
, enumerable: true })
// And adding the `greet' function
person.greet = function (person) {
return this.name + ': Why, hello there, ' + person + '.'
}
// Then we can share those behaviours with Mikhail
// By creating a new object that has it's [[Prototype]] property
// pointing to `person'.
var mikhail = Object.create(person)
mikhail.first_name = 'Mikhail'
mikhail.last_name = 'Weiß'
mikhail.age = 19
mikhail.gender = 'Male'
// And we can test whether things are actually working.
// First, `name' should be looked on `person'
mikhail.name
// => 'Mikhail Weiß'
// Setting `name' should trigger the setter
mikhail.name = 'Michael White'
// Such that `first_name' and `last_name' now reflect the
// previously name setting.
mikhail.first_name
// => 'Michael'
mikhail.last_name
// => 'White'
// `greet' is also inherited from `person'.
mikhail.greet('you')
// => 'Michael White: Why, hello there, you.'
// And just to be sure, we can check which properties actually
// belong to `mikhail'
Object.keys(mikhail)
// => [ 'first_name', 'last_name', 'age', 'gender' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment