Why Javascript Doesn’t Suck
or javascript outside the DOM
..sometimes it can suck
• Cross Browser DOM incompatibilities (and surprisingly its not all IE’s fault)
• Ugly looking code (compared to some other languages *cough* ruby *cough*)
• Poorly written code
• Global Namespace
• Lives inside the browser (it doesn’t have to)
but..
• Most widely used functional programming language ever (eat your heart out
LISP)
• lambda’s FTW
• Objects!!! (and JSON)
• Metaprogramming goodness (think ruby)
• Duck typed
• Light and easy (pretty much the opposite of Java)
you too can make it suck less
Module Pattern
var Positioning = function(){
//private members
var _x = 0;
var _y = 0;
return {
//priviledged functions, have access to private members/functions
setPosition: function(x,y){
_x = x;
_y = y;
},
getPosition: function(){
return new Array(_x, _y);
}
}
}();
Positioning.setPosition(50, 100);
Positioning.getPosition(); // [50, 100]
prototype this
prototype inheritance
function Bar(){
this.member = initializer;
return this;
}
Bar.prototype.sayHello = function(){ alert \"Hello I am Bar\"; }
var barObject = new Bar();
barObject.prototype == Bar.prototype
barObject.constructor == Bar()
barObject.sayHello() // alerts \"Hello I am Bar\"
function Foo(){
this.member = initializer;
return this;
}
Foo.prototype = new Bar();
Foo.prototype.sayHello = function(){ alert \"Hello I am Foo\"; }
var fooObject = new Foo();
fooObject.sayHello() //alerts \"Hello I am Foo\"
no more new
function object(parentObject){
//create a dummy constructor function for our new object
function F(){};
// the dummy function's prototype member is now the parentObject
F.prototype = parentObject;
// return an object with the dummy function's prototype member
return new F();
}
var bar = {
sayHello: function(){...}
};
var foo = object(bar);
foo.sayHello() // alerts “Hello I am Bar”
hold your arguments to later please
Bar.prototype.setFavoriteDrinks = function(person) {
var drinks = Array.prototype.slice.apply(arguments, [1]);
alert(person + \"'s favorite drinks are: \" + drinks.join(', '));
}
var barCamp = new Bar()
// hint ill accept any of these as a thank you later tonight
barCamp.setFavoriteDrinks(\"the dude\", \"White Russion\", \"Red Bull and Vodka\",
\"Irish Car Bomb\", \"Guiness\");
//alert \"the dude's favorite drinks are White Russion, Red Bull and Vodka, Irish
Car Bomb, Guiness\"
0 comments
Post a comment