Skip to content

Instantly share code, notes, and snippets.

@gf3
Created December 12, 2010 22:48
Show Gist options
  • Select an option

  • Save gf3/738421 to your computer and use it in GitHub Desktop.

Select an option

Save gf3/738421 to your computer and use it in GitHub Desktop.
Fancy Instances
// Proto-classy
function Book ( a_auth, a_email, options ) { var author, email
this.options = options || {}
this.options.__proto__ = Book.options
author = a_auth
email = a_email
accessor.call( this, 'author'
, function() { return 'Author: ' + author }
, function( a_auth ) { author = a_auth }
)
accessor.call( this, 'email'
, function() { return 'Email: ' + email }
, function( a_email ) { email = a_email }
)
// Instance methods
this.publish = function( url ) { }
this.update = function() { }
// Private methods
function accessor ( name, get, set ) {
this.__defineGetter__( name, get )
this.__defineSetter__( name, set )
}
}
Book.options =
{ read: false
, rating: 5
, published: false
}
// Usage
var jPad = new Book( 'Douglas Koopland', 'dougie@coupland.net' )
// Dynamic inheritence for options
console.log( jPad.options.rating ) // 5
Book.options.rating = 7
console.log( jPad.options.rating ) // 7
jPad.options.rating = 10
console.log( jPad.options ) // { rating: 10 }
// Accessors
console.log( jPad.author ) // "Author: Douglas Koopland"
jPad.author = 'Douglas Coupland'
console.log( jPad.author ) // "Author: Douglas Coupland"
@gf3

gf3 commented Dec 13, 2010

Copy link
Copy Markdown
Author

If you want ruby-style accessors, then you could clean up this implementation a bit:

accessor.call( this, 'author' )
accessor.call( this, 'email' )

// Later...
function accessor ( name ) {
  this.__defineGetter__( name, function(){ return this[ name ] } )
  this.__defineSetter__( name, function( value ){ this[ name ] = value } )
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment