JavascriptNotes
Apuntes de Javascript #
Apuntes del Javascript Bootcamp Reference.
http://slash7.com/articles/2006/07/26/javascript-boot-camp-tutorial
Para ejecutar los ejemplos de Javascript es necesario utilizar una shell de js. Por ejemplo, la disponible con la extensión de firefox:
- Extension Developer: http://ted.mielczarek.org/code/mozilla/extensiondev/
Otras consolas de Javascript:
- Web version: http://www.squarefree.com/shell/shell.html
Otras extensiones de firefox recomendables son:
- Web Developer: https://addons.mozilla.org/es-ES/firefox/addon/60
- Firebug: https://addons.mozilla.org/es-ES/firefox/addon/1843
Tipos de datos básicos #
Tipos usuales:
- Number (enteros, reales, un sólo tipo)
- String
- Booleano
Valores especiales:
- null
- undefined
Todos son objetos 'Strings'
var string = "zylk"
// --> "zylk"
var anotherString = new String("zylk net")
// --> [z,y,l,k, ,n,e,t]
string.length
// --> 4
"zylk".length
// --> 4
typeof string
// --> string
var start = anotherString.indexOf('net')
// --> 5
anotherString.substr(start)
// --> "net"
anotherString.substr(0,4)
// --> "zylk"
anotherString.substr(0,1)
// --> "z"
anotherString.substr(-1)
// --> "t"
'Numbers'
var number = 5 // --> 5 var anotherNumber = new Number(5) // --> 5 var pi = 3.14 // --> 3.14 typeof number // number typeof pi // number
'RegExps'
También son objetos:
var string = "zylk net"
string.replace(/net/, 'org')
// --> "zylk org"
var string = "zylk net"
string.replace(new RegExp("net"), 'org')
// --> "zylk org"
var z = new RegExp("net")
// --> /net/
var string = "zylk net"
string.replace(z, 'org')
// --> "zylk org"
var simpleRegExp = /\/foo/g
var anotherRegExp = new RegExp("/foo", "g")
var anotherString = "/foo /foobar"
anotherString.match(anotherRegExp)
// --> ["foo", "foo"]
anotherString.match("baz")
// --> null
anotherRegExp.test(anotherString)
// --> true
'Booleanos'
var bool = false
var anotherBool = true
if (bool) alert("Test!")
// --> ** nothing **
if (anotherBool) alert("Test!")
// --> [alert] Test!
'Null and undefined'
Valores especiales:
bool = null // --> null bool == undefined // --> true
'Arrays'
var anArray = ['foo', 'bar']
// --> ['foo','bar']
anArray.length
// --> 2
string = anArray.join(":")
// --> "foo:bar"
// Añadir un elemento al final
anArray.push('new')
// --> ['foo','bar','new']
// Recoger el ultimo elemento y borrarlo del array
var lastItem = anArray.pop()
// --> "new";
// --> anArray = ['foo','bar','baz']
Arrays Multidimensionales:
var mdArray = ['foo','bar',['baz','zort']] // --> ['foo','bar',['baz','zort']] mdArray[0][1] // // --> "o" (1st o in foo) mdArray[2][1] // --> "zort"
Localizando los valores en el array:
anArray.indexOf('foo')
// --> 0
anArray.indexOf('baz')
// --> 2
mdArray.indexOf('zort')
// --> -1 (not found! doesn't work on nested arrays)
Otros métodos usuales y esperados:
- sort()
- reverse()
- pop()
- shift()
- unshift()
- slice()
- splice()
- join()
- toString()
- valueOf()
Hashes: Objetos simples #
No hay hashes en javascripts pero los objetos más simples pueden considerarse como hashes.
var newObject = {}
newObject.foo = "bar"
// --> "bar"
newObject.foo
// --> "bar"
var anotherObject = {foo:"bar", baz:"bat"}
anotherObject.baz
// --> "bat"
Más objetos #
- Math:
- Math.sin(num),
- Math.min(a,b)
- Math.ceil(num), etc.
- Date -- for date math and so on, yay!
- date = new Date()
- day = date.getDay()
Funciones simples #
function noArgument(){
alert("Esta funcion no tiene argumentos")
}
function simpleFunction(arg1, arg2)
return arg1 + arg2
}
Se pueden pasar funciones como argumentos:
function myFunction(arg1, arg2, arg3){
// Uso el argumento 1
alert("Argumento 1: " + arg1)
// El argumento 2 es un objeto
alert(arg2.bar)
// Llamar a un argumento como una funcion
arg3()
}
myFunction("foo", {bar:"baz"}, function(){ alert("OK!") })
// [alert] Argumento 1: foo
// [alert] baz
// [alert] OK!
var myOtherFunction = function(){ just
alert("OK!")
}
myFunction("foo", {bar:"baz"}, myOtherFunction)
El objeto arguments:
function myFunction(){
alert("Argumento 1: " + arguments[0])
alert(arguments[1].bar)
arguments[2]()
}
myFunction("foo", {bar:"baz"}, myOtherFunction }
if, switch, while, do while, for ... #
'if..elseif..else'
if (something) doStuff()
if (something)
alert("OK!")
else
alert("Not OK!")
if (something == foo){
alert("es foo")
} else if (something == bar){
alert("es bar")
} else {
alert("no es nada")
}
'switch'
switch(something){
case foo:
alert("foo!!")
break
case bar:
alert("bar!!")
break
default:
alert("Caso no encontrado...")
}
'while y do while'
var i = 0;
while (i < 3){
alert(i)
i++
}
var i = 0;
do {
alert(i)
i++
} while (i < 3)
'for'
for(var i = 0; i < 3; $i++){
alert(i)
}
var anArray = ['foo', 'bar']
// --> ['foo','bar']
for(var i in anArray){
alert(i)
}
var theObject = {foo:"bar", baz:"bat"}
for (attribute in theObject){
alert(atrribute + " = " + theObject[attribute])
}
Más Strings #
Los strings actuan como arrays:
var string = "zylk"
string[0]
// --> z
string[-1]
// --> k
for(var i=0; i < string.length; i++){
alert(string[i])
}
for(var i in string){
alert(string[i])
}
Concatenar strings:
var string1 = "zylk" var string2 = "net" var string3 = string1 + " " + string2 // --> "zylk net" Conversión de tipos: 5 + "5" // --> "55"
Métodos indexOf (posicion de ) y substr (extraer string):
var anotherString = new String("zylk net")
// --> [z,y,l,k, ,n,e,t]
var start = anotherString.indexOf('net')
// --> 5
anotherString.substr(start)
// --> "net"
anotherString.substr(0,4)
// --> "zylk"
anotherString.substr(0,1)
// --> "z"
anotherString.substr(-1)
// --> "t"
Método split:
var otherArray = string.split(' ')
// --> ["zylk", "net"]
Escapar texto y codificar URL's:
var headline = "<h2>Bienvenido a zylk.net</h3>" var escaped = headline.escape() var unescaped = unescape(escaped) // --> "<h2>Bienvenido a zylk.net</h3>"
var url = "https://www.zylk.net/" var encoded = encodeURI(url) var decoded = decodeURI(encoded)
Otros métodos usuales y esperados:
- slice() - igual que substr()
- match(), replace(), search() (for using RegExps)
- toUpperCase(), toLowerCase()
- concat() - igual que el operador +
Más Objetos #
No hay clases en Javascript, todo está basado en objetos. Si quieres un constructor crea una función y esta creará un objeto. Otra manera de de crear objetos es a través de la propiedad object.prototype (Modelo de Objetos basado en Prototype)Crear un objeto usando JavaScript Object Notation (JSON):
var foo = {
aString: "bar",
aNumber: 5,
anArray: ['foo','bar'],
doStuff: function(){
alert("Stuff...")
}
}
Usando un objeto JSON:
foo.aString
// --> "bar"
for (i = 0; i < foo.anArray.length; i++){
alert(foo.anArray[i])
}
// --> [alert] foo, [alert] bar
foo.doStuff()
// --> [alert] Stuff..
Transformando strings en código:
var data = "{foo:'bar', you:'too'}"
function handleAjaxResult(ajaxResult){
eval("var result = " + ajaxResult)
alert(result.foo)
}
handleAjaxResult(data)
// --> bar
Crear un constructor con una función:
function anyFunction() {}
var object = new anyFunction()
Las funciones pueden actuar como constructores reales.
function Foo(){
this.foo = "bar"
alert("foo!!!")
}
var fooInstance = new Foo()
fooInstance.foo
// --> "bar"
Foo.prototype.bar = "bat"
Foo.prototype.fuzz = "boo"
Foo.prototype.danger = function() { alert("Alert!!" ) }
fooInstance.danger()
// --> [alert] Alert!!
fooInstance.bar
//--> "baz"
fooInstance.fuzz
// --> "boo"
Excepciones #
Ningún lenguage es completo si no maneja excepciones.
try {
doSomething(1)
} catch (e if e.name == "TypeError") {
alert("Oopps:)
} catch(e) {
alert("Uuppps: Un error del tipo " + e.name " ha ocurrido.\ El mensaje fue: " + e.message)
}
Lanzar excepciones con throw:
function doSomethingError(what){
this.name = "SomeError"
this.message = "No puedes hacer " + what
}
doSomething = function(what){
if (what){
throw new doSomethingError("booo")
}
}
El DOM #
var children = document.childNodes;
for(var i=0; i < children.length; i++) {
alert(children[i])
}
// --> [alert] [Object DocumentType]
// --> [alert] [Object HTMLHtmlElement]
var children = document.body.childNodes;
for(var i=0; i < children.length; i++) {
alert(children[i])
}
// --> [alert] [Object Text]
// --> [alert] [Object HTMLDivElement]
// --> [alert] [Object Text]
// etc
//// Finding DOM elements by DOM id
var node = document.getElementById("main")
// --> [object HTMLDivElement]
node.id
// --> "id"
node.tagName
// --> "DIV"
node.className
// --> "box"
var parent = document.getElementById("sidebar")
// --> [object HTMLDivElement]
var sidebarBlocks = parent.getElementsByTagName("div")
// --> [ div, div, div ]
for(i = 0; i < sidebarBlocks.length; i++) {
var newNode = document.createElement('p')
newNode.innerHTML = "I am #"+i
sidebarBlocks[i].appendChild(newNode)
}