Javascript ES5


Tabla de contenido

    Mostrar tabla de contenidos

ECMAScript 2009, también conocido como ES5, fue la primera revisión importante de JavaScript.

Este capítulo describe las características más importantes de ES5.

Características de ES5

  • "uso estricto"

  • Cadena[número] acceso

  • Cadenas multilínea

  • cadena.recortar()

  • matriz.isArray()

  • Matriz para cada()

  • mapa de matriz()

  • Filtro de matriz()

  • Reducir matriz()

  • Matriz reducirDerecha()

  • Matriz cada()

  • Matriz algunos()

  • Índice de matriz de()

  • Matriz último índice de()

  • JSON.parse()

  • JSON.stringify()

  • Fecha.ahora()

  • Fecha enISOString()

  • Fecha en JSON()

  • Captadores y definidores de propiedades

  • Palabras reservadas como nombres de propiedades

  • Métodos de objetos

  • Objeto definirPropiedad()

  • Función de enlace()

  • Comas al final


Soporte del navegador

ES5 es totalmente compatible con todos los navegadores modernos:

Chrome IE Edge Firefox Safari Opera
Yes 9.0 Yes Yes Yes Yes

La directiva de "uso estricto"

"use estricto" define que el código JavaScript debe ejecutarse en "modo estricto".

Con el modo estricto, por ejemplo, no puedes utilizar variables no declaradas.

Puede utilizar el modo estricto en todos sus programas. Te ayuda a escribir código más limpio, como impedirle utilizar variables no declaradas.

"use estricto" es solo una expresión de cadena. Los navegadores antiguos no arrojarán un error si no lo entienden.

Lea más en modo estricto JS.


Acceso a la propiedad en cadenas

El método charAt() devuelve el carácter en un punto especificado índice (posición) en una cadena:

Ejemplo

var str = "HELLO WORLD";
str.charAt(0);            // returns H

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The charAt() method returns the character at a given position in a string:</p>

<p id="demo"></p>

<script>
var str = "HELLO WORLD";
document.getElementById("demo").innerHTML = str.charAt(0);
</script>
</body>
</html>

ES5 permite el acceso a propiedades en cadenas:

Ejemplo

var str = "HELLO WORLD";
str[0];                   // returns H

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Methods</h2>

<p>ECMAScript 5 allows property acces on strings:</p>

<p id="demo"></p>

<script>
var str = "HELLO WORLD";
document.getElementById("demo").innerHTML = str[0];
</script>
</body>
</html>

El acceso a la propiedad en una cadena puede ser un poco impredecible.

Lea más en Métodos de cadena JS.


Cadenas en varias líneas

Ejemplo

 "Hello \
Dolly!";

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>

<p>
You can break a code line within a text string with a backslash.
</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
</script>

</body>
</html>

Es posible que el método\no tenga soporte universal.
Los navegadores más antiguos pueden tratar los espacios alrededor de la barra invertida de manera diferente.
Algunos navegadores antiguos sí lo hacen No permita espacios detrás del carácter \.

Una forma más segura de dividir un literal de cadena es usar una cadena suma:

Ejemplo

 "Hello " + 
"Dolly!";

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>

<p>The safest way to break a code line in a string is using string addition.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello " +
"Dolly!";
</script>

</body>
</html>

Palabras reservadas como nombres de propiedades

ES5 permite palabras reservadas como nombres de propiedades:

Ejemplo de objeto

 var obj = {name: "John", new: "yes"}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>ECMAScript 5</h1>

<p>ECMAScript 5 allows reserved words as property names.</p>
<p id="demo"></p>

<script>
var obj = {name: "John", new: "yes"};
document.getElementById("demo").innerHTML = obj.new;
</script>

</body>
</html>



Cadena recortar()

El método trim() elimina los espacios en blanco de ambos lados de una cadena.

Ejemplo

var str = "       Hello World!        ";
alert(str.trim());

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The trim() Method</h2>

<p id="demo"></p>

<script>
let text1 = "     Hello World!     ";
let text2 = text1.trim();

document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>

</body>
</html>

Lea más en Métodos de cadena JS.



Array.isArray()

El método isArray() comprueba si un objeto es una matriz.

Ejemplo

function myFunction() {
  var fruits = ["Banana", "Orange", "Apple", "Mango"];
  var x = document.getElementById("demo");
    x.innerHTML = Array.isArray(fruits);
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The isArray() Method</h2>

<p>Click the button to check if "fruits" is an array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  var fruits = ["Banana", "Orange", "Apple", "Mango"];
  var x = document.getElementById("demo");
  x.innerHTML = Array.isArray(fruits);
}
</script>

</body>
</html>

Lea más en JS Arrays.


Matriz paraCada()

El método forEach() llama a una función una vez para cada elemento de la matriz.

Ejemplo

var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);

function myFunction(value) {
   
txt = txt + value + "<br>"; 
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array.forEach()</h2>

<p>Calls a function once for each array element.</p>

<p id="demo"></p>

<script>
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;

function myFunction(value) {
  txt = txt + value + "<br>"; 
}
</script>

</body>
</html>

Obtenga más información en Métodos de iteración de matrices JS.


Matriz mapa()

Este ejemplo multiplica cada valor de matriz por 2:

Ejemplo

var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
  
function myFunction(value) {
  return value * 2;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array.map()</h2>

<p>Creates a new array by performing a function on each array element.</p>

<p id="demo"></p>

<script>
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);

document.getElementById("demo").innerHTML = numbers2;

function myFunction(value, index, array) {
  return value * 2;
}
</script>

</body>
</html>

Obtenga más información en Métodos de iteración de matrices JS.


Matriz filtro()

Este ejemplo crea una nueva matriz a partir de elementos con un valor mayor que 18:

Ejemplo

 var numbers = [45, 4, 9, 16, 25];
var over18 = 
  numbers.filter(myFunction);
function myFunction(value) {
  return value > 18;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array.filter()</h2>

<p>Creates a new array with all array elements that passes a test.</p>

<p id="demo"></p>

<script>
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);

document.getElementById("demo").innerHTML = over18;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

Obtenga más información en Métodos de iteración de matrices JS.


Matriz reducir()

Este ejemplo encuentra la suma de todos los números en una matriz:

Ejemplo

 var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction);
  
function myFunction(total, value) {
  
  return total + value;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array.reduce()</h2>

<p>This example finds the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
var numbers = [45, 4, 9, 16, 25];
var sum = numbers.reduce(myFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value, index, array) {
  return total + value;
}
</script>

</body>
</html>

Obtenga más información en Métodos de iteración de matrices JS.


Matriz reducirDerecha()

Este ejemplo también encuentra la suma de todos los números en una matriz:

Ejemplo

 var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduceRight(myFunction);
  
function myFunction(total, value) {
  return total + value;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array.reduceRight()</h2>

<p>This example finds the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
var numbers = [45, 4, 9, 16, 25];
var sum = numbers.reduceRight(myFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value) {
  return total + value;
}
</script>

</body>
</html>

Obtenga más información en Métodos de iteración de matrices JS.


Matriz cada()

Este ejemplo comprueba si todos los valores son mayores de 18:

Ejemplo

 var numbers = [45, 4, 9, 16, 25];
var allOver18 = 
  numbers.every(myFunction);
function myFunction(value) {
  return 
  value > 18;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array.every()</h2>

<p>The every() method checks if all array values pass a test.</p>

<p id="demo"></p>

<script>
var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.every(myFunction);

document.getElementById("demo").innerHTML = "All over 18 is " + allOver18;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

Obtenga más información en Métodos de iteración de matrices JS.


Matriz algunos()

Este ejemplo comprueba si algunos valores son mayores de 18:

Ejemplo

 var numbers = [45, 4, 9, 16, 25];
var allOver18 = 
  numbers.some(myFunction);
function myFunction(value) {
  return 
  value > 18;
} 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array.some()</h2>

<p>The some() method checks if some array values pass a test.</p>

<p id="demo"></p>

<script>
var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.some(myFunction);

document.getElementById("demo").innerHTML = "Some over 18 is " + allOver18;

function myFunction(value) {
  return value > 18;
}
</script>

</body>
</html>

Obtenga más información en Métodos de iteración de matrices JS.


Matriz indexOf()

Busca en una matriz el valor de un elemento y devuelve su posición.

Ejemplo

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The indexOf() Method</h2>

<p id="demo"></p>

<script>
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;

document.getElementById("demo").innerHTML = "Apple is found in position " + position;
</script>

</body>
</html>

Obtenga más información en Métodos de iteración de matrices JS.


Matriz lastIndexOf()

lastIndexOf() es lo mismo que indexOf(), pero busca desde el final de la matriz.

Ejemplo

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The lastIndexOf() Method</h2>

<p id="demo"></p>

<script>
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.lastIndexOf("Apple") + 1;

document.getElementById("demo").innerHTML = "Apple is found in position " + position;
</script>

</body>
</html>

Obtenga más información en Métodos de iteración de matrices JS.


JSON.parse()

Un uso común de JSON es recibir datos de un servidor web.

Imagine que recibió esta cadena de texto de un servidor web:

'{"name":"John", "age":30, "city":"New York"}'

La función JavaScript JSON.parse() se utiliza para convertir el texto en un objeto JavaScript:

var obj = JSON.parse('{"name":"John", "age":30, "city":"New 
  York"}');

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>Creating an Object from a JSON String</h2>

<p id="demo"></p>

<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>

</body>
</html>

Lea más en nuestro Tutorial JSON.


JSON.stringify()

Un uso común de JSON es enviar datos a un servidor web.

Al enviar datos a un servidor web, los datos deben ser una cuerda.

Imaginemos que tenemos este objeto en JavaScript:

var obj = {name:"John", age:30, city:"New York"};

Utilice la función JavaScript JSON.stringify() para convertirlo en una cadena.

var myJSON = JSON.stringify(obj);

El resultado será una cadena siguiendo la notación JSON.

myJSON ahora es una cadena y está listo para ser enviado a un servidor:

Ejemplo

var obj = {name:"John", age:30, city:"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>Create a JSON string from a JavaScript object.</h2>
<p id="demo"></p>

<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>

Lea más en nuestro Tutorial JSON.


Fecha.ahora()

Date.now() devuelve el número de milisegundos desde la fecha cero (1 de enero. 1970 00:00:00 UTC).

Ejemplo

var timInMSs = Date.now();

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Date.now()</h2>

<p>Date.now() is new in ECMAScript 5 (2009):</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
document.getElementById("demo1").innerHTML = Date.now();
var d = new Date();
document.getElementById("demo2").innerHTML = d.getTime();
</script>
</body>
</html>

Date.now() devuelve lo mismo que getTime() realizado en un objeto Date.

Obtenga más información en JS Dates.


Fecha toISOString()

El método toISOString() convierte un objeto Date en una cadena, utilizando el formato estándar ISO:

Ejemplo

const d = new Date();
document.getElementById("demo").innerHTML = d.toISOString();

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Dates</h1>
<h2>The toISOString() Method</h2>

<p>Convert a date to a string using the ISO standard:</p>
<p id="demo"></p>

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.toISOString();
</script>

</body>
</html>

Fecha toJSON()

toJSON() convierte un objeto Date en una cadena, formateada como una fecha JSON.

Las fechas JSON tienen el mismo formato que el estándar ISO-8601: AAAA-MM-DDTHH:mm:ss.sssZ:

Ejemplo

d = new Date();
document.getElementById("demo").innerHTML = d.toJSON();

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Date.toJSON()</h2>

<p id="demo"></p>

<script>
d = new Date();
document.getElementById("demo").innerHTML = d.toJSON();
</script>

</body>
</html>

Captadores y Definidores de Propiedades

ES5 le permite definir métodos de objeto con una sintaxis que parece obtener o configurar una propiedad.

Este ejemplo crea un getter para una propiedad llamada nombre completo:

Ejemplo

 // Create an object:
var person = {
  firstName: 
  "John",
  lastName : "Doe",
  get 
  fullName() {
    
  return this.firstName + " " + this.lastName;
  }
};
// Display data from the 
  object using a getter:
document.getElementById("demo").innerHTML = 
  person.fullName; 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Getters and Setters</h2>

<p>Getters and setters allow you to get and set properties via methods.</p>

<p>This example creates a getter for a property called fullName.</p>

<p id="demo"></p>

<script>
// Create an object:
var person = {
  firstName: "John",
  lastName : "Doe",
  get fullName() {
    return this.firstName + " " + this.lastName;
  }
};
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.fullName;
</script>

</body>
</html>

Este ejemplo crea un setter y un getter para la propiedad de idioma:

Ejemplo

 var person = {
  firstName: "John",
  
  lastName : "Doe",
  language : "NO",
  
  get lang() {
    return this.language;
  },
  set lang(value) {
    
  this.language = value;
  }
};
// Set an object 
  property using a setter:
person.lang = "en";
// Display data from the 
  object using a getter:
document.getElementById("demo").innerHTML = 
  person.lang;
 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Getters and Setters</h2>

<p>Getters and setters allow you to get and set properties via methods.</p>

<p>This example creates a setter and a getter for the language property.</p>

<p id="demo"></p>

<script>
// Create an object:
var person = {
  firstName: "John",
  lastName : "Doe",
  language : "NO",
  get lang() {
    return this.language;
  },
  set lang(value) {
    this.language = value;
  }
};
// Set an object property using a setter:
person.lang = "en";
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;
</script>

</body>
</html>

Este ejemplo utiliza un configurador para proteger las actualizaciones del idioma en mayúsculas:

Ejemplo

 var person = {
  firstName: "John",
  
  lastName : "Doe",
  language : "NO",
  set lang(value) {
    
  this.language = value.toUpperCase();
  }
};
// Set an object 
  property using a setter:
person.lang = "en";
// Display data from the 
  object:
document.getElementById("demo").innerHTML = 
  person.language;
 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Getters and Setters</h2>

<p>Getters and setters allow you to get and set properties via methods.</p>

<p>This example has a modified setter to secure upper case uppdates of language.</p>

<p id="demo"></p>

<script>
// Create an object:
var person = {
  firstName: "John",
  lastName : "Doe",
  language : "",
  set lang(value) {
     this.language = value.toUpperCase();
  }
};
// Set an object property using a setter:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;
</script>

</body>
</html>

Obtenga más información sobre Gettes y Setters en accesorios de objetos JS


Objeto.defineProperty()

Object.defineProperty() es un nuevo método de objeto en ES5.

Le permite definir una propiedad de objeto y/o cambiar el valor de una propiedad y/o metadatos.

Ejemplo

 // Create an Object:
var person = {
  firstName: 
  "John",
  lastName : "Doe",
  language : "NO", 
};

  // Change a Property:
Object.defineProperty(person, "language", {
    
  value: "EN",
  writable : true,
  enumerable : true,
  configurable : true
});
// 
  Enumerate Properties
var txt = "";
for (var x in person) {
    
  txt += person[x] + "<br>";
}
document.getElementById("demo").innerHTML = 
  txt;
 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>

<head>
<meta content="text/html; charset=iso-8859-2" http-equiv="Content-Type">
</head>

<body>

<h2>JavaScript defineProperty()</h2>

<p id="demo"></p>

<script>
// Create an Object:
var person = {
  firstName: "John",
  lastName : "Doe",
  language : "NO", 
};
// Change a Property:
Object.defineProperty(person, "language", {
  value: "EN",
  writable : true,
  enumerable : true,
  configurable : true
});
// Enumerate Properties
txt = "";
for (var x in person) {
  txt += person[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>

El siguiente ejemplo es el mismo código, excepto que oculta la propiedad del idioma de la enumeración:

Ejemplo

 // Create an Object:
var person = {
  firstName: 
  "John",
  lastName : "Doe",
  language : "NO", 
};

  // Change a Property:
Object.defineProperty(person, "language", {
    
  value: "EN",
  writable : true,
  enumerable : false,
  configurable : true
});
// 
  Enumerate Properties
var txt = "";
for (var x in person) {
    
  txt += person[x] + "<br>";
}
document.getElementById("demo").innerHTML = 
  txt;
 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript defineProperty()</h2>

<p id="demo"></p>

<script>
// Create an Object:
var person = {
  firstName: "John",
  lastName : "Doe",
  language : "NO", 
};
// Change a Property:
Object.defineProperty(person, "language", {
  value: "EN",
  writable : true,
  enumerable : false,
  configurable : true
});
// Enumerate Properties
txt = "";
for (var x in person) {
  txt += person[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>

Este ejemplo crea un definidor y un captador para asegurar las actualizaciones del idioma en mayúsculas:

Ejemplo

 // Create an Object:
var person = {
  firstName: "John",
    lastName : 
  "Doe",
  language : "NO"
};
// Change a Property:
  Object.defineProperty(person, "language", {
  get : function() { return 
  language },
  set : function(value) { language = value.toUpperCase()}
});

  // Change Language
person.language = "en";
// Display Language
  document.getElementById("demo").innerHTML = person.language;

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript defineProperty()</h2>

<p id="demo"></p>

<script>
// Create an Object:
var person = {
  firstName: "John",
  lastName : "Doe",
  language : "NO"
};
// Change a Property:
Object.defineProperty(person, "language", {
  get : function() { return language },
  set : function(value) { language = value.toUpperCase()}
});
// Change language
person.language = "en";
// Display language
document.getElementById("demo").innerHTML = person.language;
</script>

</body>
</html>

Métodos de objetos E5

ES5 agregó muchos métodos de objetos nuevos a JavaScript:

Administrar objetos

// Create object with an existing object as prototype
Object.create(parent, donor)

// Adding or changing an object property
Object.defineProperty(object, property, descriptor)

// Adding or changing object properties
Object.defineProperties(object, descriptors)

// Accessing Properties
Object.getOwnPropertyDescriptor(object, property)

// Returns all properties as an array
Object.getOwnPropertyNames(object)

// Accessing the prototype
Object.getPrototypeOf(object)

// Returns enumerable properties as an array
Object.keys(object)

Proteger objetos

// Prevents adding properties to an object
Object.preventExtensions(object)

// Returns true if properties can be added to an object
Object.isExtensible(object)

// Prevents changes of object properties (not values)
Object.seal(object)

// Returns true if object is sealed
Object.isSealed(object)

// Prevents any changes to an object
Object.freeze(object)

// Returns true if object is frozen
Object.isFrozen(object)

Obtenga más información en Objeto ECMAScript5.


Función Vincular()

Con el método bind(), un objeto puede tomar prestado un método de otro objeto.

Este ejemplo crea 2 objetos (persona y miembro).

El objeto miembro toma prestado el método de nombre completo del objeto persona:

Ejemplo

const person = {
  firstName:"John",
  lastName: "Doe",
    fullName: function () {
    return this.firstName + " " + this.lastName;
    }
}

const member = {
  firstName:"Hege",
  lastName: "Nilsen",
}

let fullName = person.fullName.bind(member);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Function bind()</h1>

<p>This example creates 2 objects (person and member).</p>
<p>The member object borrows the fullname method from person:</p> 

<p id="demo"></p>

<script>
const person = {
  firstName:"John",
  lastName: "Doe",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}

const member = {
  firstName:"Hege",
  lastName: "Nilsen",
}

let fullName = person.fullName.bind(member);

document.getElementById("demo").innerHTML = fullName();
</script>

</body>
</html>

Obtenga más información en Función vincular().


Comas finales

ES5 permite comas finales en definiciones de objetos y matrices:

Ejemplo de objeto

person = {
  firstName: "John",
  lastName: "
Doe",
	age: 46,
}

Ejemplo de matriz

points = [
  1,
  5,
  10,
  25,
  40,
  100,
];

ADVERTENCIA !!!

JSON no permite comas finales.

Objetos JSON:

 //
  Allowed:
var person = '{"firstName":"John", "lastName":"Doe", 
  "age":46}'
JSON.parse(person)
// Not allowed:
var person = '{"firstName":"John", 
  "lastName":"Doe", "age":46,}'
JSON.parse(person)

Matrices JSON:

   //
    Allowed:
points = [40, 100, 1, 5, 25, 10]
// Not allowed:
points = 
    [40, 100, 1, 5, 25, 10,]