Created
June 27, 2012 02:07
-
-
Save anthonybrown/3000860 to your computer and use it in GitHub Desktop.
JavaScripts Good Parts
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
var add = function(a,b) { | |
return a + b; | |
} | |
var times = function(a,b) { | |
return a * b; | |
} | |
console.log( add( 6, 4 ) ); | |
console.log( times( 6, 4 ) ); | |
// Method invocation pattern | |
var myObj = { | |
value: 0, | |
increment: function(inc) { | |
// taking the current value and checking to see if it is not a number than add 1 | |
this.value += typeof inc === 'number' ? inc : 1; | |
} | |
}; | |
myObj.increment(); | |
console.log(myObj.value); | |
myObj.increment(4); | |
console.log(myObj.value); | |
// The function invocation pattern | |
var sum = add(3,5); | |
// When a function is invoked with this pattern, this is bound to the global object. | |
// This was a mistake in the design of the language. | |
// Augmenting the myObj with a double method. | |
myObj.double = function() { | |
// A workaround | |
var that = this; | |
var helper = function() { | |
that.value = add(that.value, that.value); | |
}; | |
// Invoke helper as a function | |
helper(); | |
}; | |
// Invoke double as a method. | |
myObj.double(); | |
console.log(myObj.value); | |
// The constructor invocation pattern | |
//Creat a constructor named Quo | |
//It takes an object with a status property. | |
var Quo = function (string) { | |
this.status = string; | |
}; | |
// Give all instances of Quo a public method | |
// called get_status. | |
Quo.prototype.get_status = function() { | |
return this.status; | |
}; | |
// Make an instance of Quo | |
var myQuo = new Quo('I am confused now\nhow did I do that?'); | |
console.log(myQuo.get_status()); | |
// The apply invocation pattern | |
// Make an array of 2 numbers and add them. | |
var array = [3, 4]; | |
var sum = add.apply(null, array); | |
console.log(sum); | |
// make an object with a status member | |
var statusObj = { | |
status: 'A-Okay!' | |
}; | |
// statusObj does not inherit from Quo.prototype, | |
// but we can invoke the get_status method on | |
// statusObj even though statusObj does not have | |
// a get_status method. | |
var status = Quo.prototype.get_status.apply(statusObj); | |
console.log(status); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment