Last active
December 12, 2015 08:48
-
-
Save constantology/4746471 to your computer and use it in GitHub Desktop.
example code for comment to blog post: http://evanprodromou.name/2013/02/08/on-using-this-exactly-once/
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
function Person(/* whatever args your gonna have*/) { | |
this.onSave_ = this.onSave.bind( this ); | |
this.onSetAge_ = this.onSetAge.bind( this ); | |
} | |
Person.prototype.save = function() { | |
this.database.insert( this.properties, this.onSave_ ); | |
}; | |
Person.prototype.setAge = function( newAge ) { | |
this.constructor.validate( "age", this, newAge, this.onSetAge_ ); | |
}; | |
Person.prototype.onSave = function( err, result ) { | |
if ( err ) | |
throw err; | |
this.properties = result; | |
}; | |
Person.prototype.onSetAge = function( err, result ) { | |
if ( err ) | |
throw err; | |
this.age = result; | |
}; |
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
;!function( Super ) { | |
function ExquisitePerson() { | |
Super.apply( this, arguments ); | |
} | |
ExquisitePerson.validate = Super.validate; | |
ExquisitePerson.prototype = Object.create( Super.prototype ); | |
ExquisitePerson.prototype.setAge = function( newAge ) { | |
newAge *= .67; // equisite type persons age much more slowly than normal sucker type persons | |
Super.prototype.setAge.apply( this, arguments ); | |
}; | |
ExquisitePerson.prototype.onSave = function( err, result ) { | |
Super.prototype.onSave.apply( this, arguments ); | |
// do something exquisite here to disriminate against normal sucker type persons in favour of equisite type persons | |
}; | |
}( Person ); |
@TryingToImprove I find the best explanations to IIFE in http://benalman.com/news/2010/11/immediately-invoked-function-expression/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@TryingToImprove I believe the ; at the beginning is a guard against other js files that can come before this file during concatenation. Basically if those other js files make use of automatic semicolon insertion, that might cause some problems. There was a lot of discussion about this when Twitter Bootstrap coders refused to use semicolons, and this caused problems for some people (especially those using Crockford's JSMin).
The ! is there since function () {}() is not valid. An alternative, and I think better version is (function () {})(). This is called an immediately invoked function expression (IIFE). See http://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function for more info.