Formas de crear un objeto:
Literales
var user1 = {
name: 'Lenin',
lastName: 'Meza',
address: {
country: 'Mexico',
zc: '01000'
}
};
Palabra clave new
var user2 = new Object();
user2.name = 'Lenin';
user2.lastName = 'Lenin';
user2.address = new Object();
user2.address.country = 'Mexico';
user2.address.zc = '01000';
Función Constructor
var Person = function(name, lastName, address) {
this.name = name;
this.lastName = lastName;
this.address = address;
}
var user3 = new Person("Lenin", "Meza", {country: "Mexico", zp: "01000"});
Acceder a las propiedades:
person.first:
person.last:
person.full():
Constructor
person2 arguments:
person2.first:
person2.last:
Method
person2.fullName():
Prototype
person2.nationality:
// Objeto simple
var person = {
first: "Lenin",
last: "Meza",
full: function() {
return this.first + " " + this.last;
}
};
// Definición de la función
function PersonFn(first, last) {
// Argumentos pasados al constructor
console.log('arguments', arguments);
// Asignar los argumentos a variables locales
this.first = first;
this.last = last;
// Métodos
this.changeName = function (name) {
this.first = name;
}
}
// Instancia de la función
var person2 = new PersonFn("", "Meza");
// Llamar a método
person2.changeName("Lenin");
// Agregar método a un prototype existente
PersonFn.prototype.nationality = "Mexican";
Call:
Call:
Apply:
Apply / Math.max:
Apply / Math.min:
Apply:
// Call
var greet = function(name1, name2) {
return this.toUpperCase() + ' ' + name1 + ' y ' + name2;
}
var names = ['Tom', 'Jerry'];
greet.call('hola', names[0], names[1]);
// Apply
var greet = function(name1, name2) {
return this.toUpperCase() + ' ' + name1 + ' y ' + name2;
}
var names = ['Tom', 'Jerry'];
greet.apply('hola', names);
IIFE: Immediately Invoked Function Expressions
count.inc():
count.inc():
count.getCount():
count.dec():
count.getCount():
var count = (function() {
var x = 0;
var inc = function() {
return x++;
}
var dec = function() {
return x--;
}
var getCount = function() {
return x;
}
return {
inc: inc,
dec: dec,
getCount: getCount,
};
})();
count.inc();
count.inc();
count.getCount();
count.dec();
count.getCount();
stringify:
key/value:
delete (myObj.object):
parse date:
eval:
var myObj = {
"string": "Lenin",
"number": 30,
"boolean": true,
"null": null,
"object": {
"foo": "bar"
},
"array": [
1, 2, 3
],
"birth":"1986-06-14",
"func": "function () {return this.number;}"
};
JSON.stringify(myObj);
delete myObj.object;
var parsed = JSON.parse(JSON.stringify(myObj), function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}
});
parsed.birth;
parsed.func = eval("(" + parsed.func + ")");
parsed.func();
yourName: {{ yourName }}
father.getFullName(): {{ father.getFullName() }}
mother.getFullName(): {{ mother.getFullName() }}