Created
January 11, 2016 11:33
-
-
Save mmfilesi/9a0fb2159e12ce3ca3de to your computer and use it in GitHub Desktop.
javaScript orientado a objetos (1)
This file contains hidden or 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
<!DOCTYPE html> | |
<html class="no-js"> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<title></title> | |
<meta name="description" content=""> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
</head> | |
<body> | |
<script> | |
'use strict'; | |
/* ================================ | |
1. Creación de objetos | |
================================ */ | |
/* Los objetos se pueden crear de tres maneras: */ | |
/* a - Notación de literales */ | |
var objetoUno = { | |
propiedad: 'bar', | |
metodo: function() { | |
console.log(this.propiedad); | |
} | |
}; | |
objetoUno.metodo(); // "bar" | |
/* b - Función constructora */ | |
var ClaseUno = function(foo) { | |
var self = this; | |
var _propiedadPrivada = 2; | |
var _metodoPrivado = function() { | |
return self.propiedadPublica + _propiedadPrivada; | |
}; | |
this.propiedadPublica = 0; | |
this.metodoPublico = function() { | |
this.propiedadPublica = foo; | |
console.log(_metodoPrivado()); // 6 | |
} | |
}; | |
var miInstancia = new ClaseUno(4); | |
console.log(miInstancia); | |
/* metodoPublico: () | |
propiedadPublica: */ | |
miInstancia.metodoPublico(); | |
/* c - Object.create() */ | |
/* Sintaxis básica: | |
var miObjeto = Object.create(proto [, propertiesObject ]); */ | |
var animal = Object.create(Object.prototype, { | |
comer: { | |
value: "ñam, ñam" | |
}, | |
dormir: { | |
value: "zzzzz..." | |
} | |
}); | |
var gato = Object.create(animal); | |
console.log(gato.comer); // ñam, ñam | |
/* propiedades-descriptoras o propiedades-atributo y son: | |
value: el valor de la propiedad. Puede ser cualquier valor habitual de una variable (una cadena de texto, un número, un valor booleano, una función...). Por defecto es undefined. | |
writable: («escribible»). Un valor booleano que indica si se puede (true) o no (false) modificar. Por defecto es false. | |
enumerable: si debe mostrarse (true) o no (false) en una enumeración for... in. Por defecto es false. | |
configurable: si se puede (true) o no (false) modificar de alguna manera, por ejemplo, borrándola o cambiando los valores de las demás propiedades descriptoras. Por defecto es false. | |
Object.defineProperty( | |
animal, | |
"dormir", | |
{ value: "zzzz...", | |
writable: true, | |
enumerable: true, | |
configurable: true } | |
); | |
*/ | |
/* ================================ | |
2. Prototype | |
================================ */ | |
var miObjeto = function() { | |
this.propiedad = 10; | |
this.metodo = function() { | |
console.log(this.propiedad); | |
} | |
}; | |
miObjeto.prototype.miMetodoPrototipado = function miOtroMetodo() { | |
console.log(this.propiedad+5); | |
} | |
miInstancia = new miObjeto; | |
miInstancia.metodo(); // 10 | |
miInstancia.miMetodoPrototipado(); // 15 | |
console.log("c", miInstancia.constructor) | |
/* ================================ | |
3. El this enloquecido | |
================================ */ | |
/* this hace referencia al objeto desde el que se invoca una función o método, es decir, al contexto de la función. */ | |
/* var MiClase = function() { | |
this.foo = "bar"; | |
this.bazinga = function() { | |
console.log(this.foo); // bar | |
console.log(this); // MiClase | |
function yuk() { | |
console.log(this.foo); // undefined | |
console.log(this); // Window o0 | |
} | |
yuk(); | |
} | |
} | |
miInstancia = new MiClase(); | |
miInstancia.bazinga(); */ | |
/* La solución es cachear this */ | |
var MiClase = function() { | |
var self = this; | |
this.foo = "bar"; | |
this.bazinga = function() { | |
function yuk() { | |
console.log(self.foo); // bar | |
console.log(self); // MiClase | |
} | |
yuk(); | |
} | |
}; | |
/* ================================ | |
4. Apply, call, bind | |
================================ */ | |
/* Con el método call() podemos cambiar el valor de this, que pasa ser el que indiquemos en su primer parámetro. Además, si fuera necesario, podemos pasar los n parámetros que demande la función. */ | |
function sumar(numero) { | |
/* this = 2 y numero = 5 */ | |
console.log(this+numero); // 7 | |
} | |
sumar.call(2, 5); | |
/* El método apply() es muy parecido, solo que además del valor de this se le puede pasar un array de argumentos. */ | |
function suma() { | |
var resultado = 0; | |
var i = 0; | |
var len = arguments.length; | |
for (; i<len; i++) { | |
resultado += this + arguments[i]; | |
} | |
return resultado; | |
} | |
var numeros = [1, 4, 5]; | |
console.log( suma.apply(2, numeros) ); // 16 | |
/* bind() crea una nueva función idéntica a la original, pero en la que podemos definir qué valor tendrá this. */ | |
function bazinga() { | |
console.log(this.cantar); | |
} | |
/* Aquí bazinga es undefined, ya que no tiene la propiedad cantar | |
bazinga(); */ | |
var miObjetoBind = { | |
cantar: "Oh la la!" | |
}; | |
miObjetoBind.miMetodo = bazinga.bind(miObjetoBind); | |
/* Aquí bazinga es Oh la la!, ya que ahora this sí que está definido, es miObjeto */ | |
miObjetoBind.miMetodo(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you Very Much !!!