Javascript
Recursos
https://uniwebsidad.com/libros/javascript
https://github.com/sergarb1/ApuntesDWEC
https://developer.mozilla.org/es/docs/Web/JavaScript/Guide
https://developer.mozilla.org/es/docs/Learn
https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/README.md
https://exploringjs.com/es6/index.html
https://exploringjs.com/impatient-js/toc.html
https://eloquentjavascript.net/
https://losapuntesdemajo.vercel.app/
https://fullstackopen.com/en/#course-contents
https://www.theodinproject.com/
Practicar
Integrar Javascript en HTML
<script type="text/javascript">�// codi�</script>
<script type="text/javascript" src="scripts.js"></script>
<noscript>�<p> El teu navegador no suporta javascript. </p>�</noscript>
// Hi ha gent que el fica baix del tot per a que estiga tot el document carregat.
Ocultar el codi Javascript
var _0x47a0=['log','Hello\x20World!']; (function (_0x558f55,_0x47a08a){var _0x257f99= function (_0x256ed6) {while(--_0x256ed6) {_0x558f55['push'] (_0x558f55['shift']()); }};_0x257f99(++_0x47a08a);}(_0x47a0,0x1cb));var _0x257f =function(_0x558f55,_0x47a08a){_0x558f55=_0x558f55-0x0;var _0x257f99=_0x47a0[_0x558f55];return _0x257f99;};function hi(){console[_0x257f('0x1')](_0x257f('0x0'));}hi();
ECMA
Comentaris
// Comentari d’una línia
/* Comentari �de�varies línies */
Declaració de Variables
a = 1;
var a = 1;
let a = 1;
const a = 1;
var a;�a = 1;
window.a = 1;
No recomanable. (Prohibit a classe)
Són globals es declaren on es declaren.
Única manera abans de ES6. Ja no hi ha motiu per utilitzar-lo. (Prohibit a classe)
Soluciona problemes de scope de var.
No es pot declarar dues vegades.
No es pot reasignar el valor.
Declaració amb valor ‘undefined’.
Assignació del valor.
Equivalent a variable global, però el codi queda més clar.
Tipus de variables
x = 1 ;
x = '1' ;
"1234" * 1 === 1234
2 / "bla bla" -> NaN
Tipus suportats
Tipus | Exemple | Descripció |
Cadena | "Hola Mon" | Caràcters dins de cometes |
Número | 9.34 | Números en . per a decimals |
Boolean | true | true o false |
Null | null | Sense valor |
Function | | Una funció és referenciable com una variable |
Object | | Objectes com arrays o altres |
typeOf()
let array_mix = [
"abcdef", 2 , 2.1 , 2.9e3 , 2e-3 ,
0o234 , 0x23AF , true , [1,2,3] , {'a': 1, 'b': 2}
];
for (let i=0;i<array_mix.length;i++) {
console.log(typeof(array_mix[i]));
}
Conversions
True, False, Truthy, Falsy
Funcions
Funcions
function suma_y_mostra(numero1,numero2) {
let resultat = numero1 + numero2;
alert("El resultat és " + resultat);
return resultat;
}
Declaració de funció
(En temps de compilació)
Funcions com a variables
function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); }
let x = toCelsius(77);
console.log(`La temperatura és: ${x} C`);
// Dirèctament en la variable
x = function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); }
console.log(`La temperatura és: ${x(77)} C`);
// Sense nom de funció
x = function (fahrenheit) { return (5/9) * (fahrenheit-32); }
console.log(`La temperatura és: ${x(77)} C`);
Expressió de funció
(En temps d'execució)
(No hoising)
Àmbit de les funcions
console.log(square(5)); // 25
/* ... */
function square(n) { return n*n }
console.log(square); // undefined
console.log(square(5)); // TypeError
let square = function (n) {
return n * n;
}
Àmbit (Scope)
Global
var a = 1;
function global() {
console.log(a);
}
global();
console.log(a);
Local o de funció
function local() {� var a = 2;� console.log(a);�}�local();�console.log(a);
De bloc
for (let i = 0; i < 10; i++) {
console.log(i);
}
console.log(i); // error
Àmbit de les variables en funcions
function addSquares(a,b) {
function square(x) {
return x * x;
}
return square(a) + square(b);
}
a = addSquares(2,3); // retorna 13
b = addSquares(3,4); // retorna 25
c = addSquares(4,5); // retorna 41
function outside(x) {
function inside(y) {
return x + y;
}
return inside;
}
let fn_inside = outside(3);
let result = fn_inside(5); // retorna 8
let result1 = outside(3)(5); // retorna 8
Funcions anònimes
let nums = [0,1,2];
let doubledNums = nums.map( function(element){ return element * 2; } ); // [0,2,4]
let foo = function(){ /*...*/ };
Constructor Function
var suma = new Function('a','b',"return a + b ");
console.log(suma(10,20));
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
persona = { nom: 'Pepe',cognom: 'Garcia',
consulta: function () { return `${this} ${this.nom} ${this.cognom}`},
consultar: () => `${this} ${this.nom} ${this.cognom}`
}
console.log(persona.consulta(), persona.consultar());
Funcions auto-invocades
(function () {
var aName = "Barry";
})();
aName // "Uncaught ReferenceError: aName is not defined"
var result = (function () {
var name = "Barry";
return name;
})();
result; // "Barry"
Arguments per defecte
var x = function(x=2, y=2) {
return x * y;
}
var multi = function(x,y){
if (x === undefined) {x=2;}
if (y === undefined) {y=2;}
console.log(arguments.length); // és un array
return x*y;
}
Elements del llenguatge
Operadors de comparació
Estructures de control
if ( a === 1 ) { ... } else { … }
let h = a < b ? 5 : 10 ;
for (let i = 0 ; i < 10 ; i++) {...}
for (let i of array) {...}
while ( i <= 10 ) {...}
do {...} while (i <= 10)
a === 1 && {...} || {...}
Comunicació amb l'usuari
console.log('"We don\'t make mistakes. We just have happy accidents." - Bob Ross'); // escapant la ''
console.log("\"We don't make mistakes. We just have happy accidents.\" - Bob Ross"); // escapant les ""
console.log(`"We don't make mistakes. We just have happy accidents." - Bob Ross`); // escapant amb `
console.log('Homer J. Simpson\n' + '742 Evergreen Terrace\n' + 'Springfield'); // Multiples línies
console.log(`Homer J. Simpson
742 Evergreen Terrace
Springfield`); // En ` es pot fer literal
let a = 2; console.log('La variable a val: '+a); // concatenant string i número
console.log('La variable a val:',a); // log accepta varis arguments
console.log(`La variable a val: ${a}`); //La millor manera, amb ${}
console.log(`${host}/login/oauth/authorize?client_id=${clientId}&scope=${scope}`); // millor per a moltes variables
let edat = 19; console.log(`L'alumne és: ${edat < 18 ? 'menor' : 'major' }`) // es pot clavar una expressió
function miTaggedTemplateLiteral(strings, ...values) {
return console.log(strings, ...values);
}
let nombre = "Carlos";
let edad = 32;
miTaggedTemplateLiteral`Hola soy ${nombre} y tengo ${edad} años`;
// ["Hola soy ", " y tengo ", " años"]
// "Carlos"
// 32
Arrays
Arrays
Recorrer Arrays
for (let i =0; i< a.length; i++){ console.log(a[i]);}
for (let i of a){console.log(i);}
a.forEach(i => console.log(i))
a.map(i=> console.log(i)); // en aquest cas, millor forEach
const alligator = ["thick scales", 80, "4 foot tail", "rounded snout"];
alligator.includes("thick scales"); // returns true
alligator.find(el => el.length < 12); // returns '4 foot tail'
alligator.find((el, idx) => typeOf(el) === "string" && idx === 2); // returns '4 foot tall'
alligator.indexOf("rounded snout"); // returns 3
alligator.findIndex(el => el == "rounded snout"); // returns 3
alligator.filter(el => el === 80); //returns [80]
Altres operacions en Arrays
Escacs
Arrays
Use strict
Objectes i classes
Objectes
let persona = {
nombre: ['Bob', 'Smith'], edad: 32, genero: 'masculino', intereses: ['música', 'esquí'],
bio: function () {
alert(this.nombre[0] + '' + this.nombre[1] + ' tiene ' + this.edad + ' años. Le gusta ' + this.intereses[0] + ' y ' + this.intereses[1] + '.');
}};
for .. in
let user = { name: "John", age: 30 };
alert( "age" in user ); // true, user.age exists
alert( "blabla" in user ); // false, user.blabla doesn't exist
let user = {
name: "John",
age: 30,
isAdmin: true
};
for (let key in user) {
// keys
alert( key ); // name, age, isAdmin
// values for the keys
alert( user[key] ); // John, 30, true
}
Objecte predefinit: String
Objecte predefinit: Date
// Crea una data amb la data i hora del sistema
var d=new Date();
// Crea una data amb una cadena
d=new Date("October 13, 2014 11:13:00");
// Crea una data amb any, mes, dia, hora, minuts, segons, milisegons
d=new Date(99,5,24,11,33,30,0);
// Crea una data amb any mes i dia
d=new Date(99,5,24);
Objecte predefinit: Date
Objecte predefinit: Array
Objecte predefinit: Math
Altres objectes predefinits
Classes
Objectes amb funcions (Mètodes �interns)
function Apple (type) {
this.type = type;
this.color = "red";
this.getInfo = function() {
return this.color + ' ' + this.type + ' apple';
};
}
Objectes amb funcions (Mètodes en prototype)
function Apple (type) {
this.type = type;
this.color = "red";
}
Apple.prototype.getInfo = function() {
return this.color + ' ' + this.type + ' apple';
};
Objectes literals
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
Singleton amb una funció
var apple = new function() {
this.type = "macintosh";
this.color = "red";
this.getInfo = function () {
return this.color + ' ' + this.type + ' apple';
};
}
Què és Prototype
var homework = {
topic: "JS"
};
homework.toString(); // [object Object]
La funció toString() està en Object.prototype
Object Linkage
var homework = {
topic: "JS"
};
var otherHomework = Object.create(homework);
otherHomework.topic; // "JS"
Prototype Chain
Prototype en Objectes i Funcions
Prototype en Objectes predefinits
Array.prototype.forEachLog = function(){ for(let i of this) console.log(i)
}
let a = [1,2,3,4]
a.forEachLog()
Object.defineProperty(Array.prototype, 'foeachLog', {
value: function() { for(let i of this) console.log(i) }
});
Molt problematic, ja que passa a ser un atribut accesible en for .. in
const copyOfObject = {...originalObject};
const copyOfArray = [...originalArray];
Object.assign({},originalObject)
let copyOfObject = structuredClone(originalObject)
// Desestructuració d'arrays
const foo = ['uno', 'dos', 'tres'];
const [rojo, amarillo, verde] = foo;
console.log(rojo); // "uno"
console.log(amarillo); // "dos"
console.log(verde); // "tres"
// Desestructuració d'objectes
const o = {p: 42, q: true, a: {r: 20, s: 'abc'}};
const {p, q} = o;
console.log(p,q); // 42 true
const {p: foo, q: bar} = o; // Nous noms
console.log(foo,bar); // 42 true
var {a} = o;
var {a: {r: R}} = o; // Objectes anidats i canvi de nom
console.log(a,R);
Object Destructuring en Funcions
class Chameleon { // Amb valors per defecte
constructor({ newColor = "green" } = {}) {
this.newColor = newColor;
}
}
const freddie = new Chameleon({ newColor: "purple" });
const user = {
id: 42,
displayName: "jdoe",
fullName: { firstName: "John", lastName: "Doe", },
};
function userId({ id }) {
return id;
}
function whois({ displayName, fullName: { firstName: name } }) { return `${displayName} es ${name}`;}
console.log(userId(user)); // 42
console.log(whois(user)); // "jdoe es John"
Object Literal enhacement
const a = 'foo';
const b = 42;
const c = {};
const object1 = { a, b, c }; // No cal fer a: a, b: b ...
console.log(object1); // Object { a: "foo", b: 42, c: {} }
Classes amb class (ES6)
const x = function() {}
const y = class {}
const constructorFromFunction = new x();
const constructorFromClass = new y();
Exemple de creació de classes
function Hero(name, level) {
this.name = name;
this.level = level;
}
class Hero {
constructor(name, level) {
this.name = name;
this.level = level;
}
}
Exemple de creació de mètodes
function Hero(name, level) {
this.name = name;
this.level = level;
}
Hero.prototype.greet = function() {
return `${this.name} says hello.`;
}
class Hero {
constructor(name, level) {
this.name = name;
this.level = level;
}
greet() {
return `${this.name} says hello.`;
}
}
Herència
// Creant un nou constructor a partir del pare
function Mage(name, level, spell) {
// Enllaçar constructors amb call()
Hero.call(this, name, level);
this.spell = spell;
}
class Mage extends Hero {
constructor(name, level, spell) {
// Enllaçar constructors amb super
super(name, level);
this.spell = spell;
}
}
Atributs estàtics
class Foo {
constructor(prop) {
this.prop = prop;
}
static staticMethod() {
return 'classy';
}
prototypeMethod() {
return 'prototypical';
}
}
const foo = new Foo(123);
Classes i atributs privats
class SmallRectangle {
constructor() { let width = 20; let height = 10;
this.getDimension = () => { return {width: width, height: height};};
this.increaseSize = () => { width++; height++; }; }
}
const rectangle = new SmallRectangle();
console.log(rectangle.getDimension());
console.log(rectangle.height); // => undefined
console.log(rectangle.width); // => undefined
Closure
const add = (function () { // Funció autoinvocada
let counter = 0; // Closure
return function () {counter += 1; return counter} // add serà aquesta funció
})();
console.log(add()); // 1
console.log(add()); // 2
Closure
function triangle(a,b){
this.a = a;
this.b = b; // Amb this es queda al prototype i és accessible
console.log(this);
let hipo = Math.sqrt(this.a*this.a + this.b*this.b); // no és accessible
this.hipotenusa = function (){
return `La Hipotenusa es: ${hipo}`; // La funció sí que té accés
}
}
let t = new triangle(10,20); // prova a llevar el new
console.log(t.hipotenusa(),t.hipo); // 22.36 undefined
Setters i Getters
class Producte {
constructor(nom,preu){
this.nom = nom; this.preu = preu;
}
set setPreu(preu){
if(isNaN(preu)) this.preu = 0;
else this.preu = preu
}
get getPreu(){
return parseFloat(this.preu);
}
}
let p1 = new Producte(PC,1000);
p1.setPreu = 900;
function classroom(teacher) {
//"use strict"; // prova el mode estricte
this.plant = 3; // sense new, this és window
console.log(this);
return function study() {
console.log(
`${ teacher } says to study ${ this.topic } in plant ${this.plant}`
);};}
let assignment = classroom("Kyle"); // Prova a ficar el new
console.log(assignment);
assignment();
let clase = { topic: 'mates',
plant: '5', // prova a comentar aquesta línia
assignment: assignment
}
clase.assignment();
This segons com invoquem
// Simple Invocation
function simpleInvocation() {console.log(this);}
simpleInvocatoin();
// Method Invocation
const methodInvocation = { method(){ console.log(this);}};
methodInvocation.method();
// Indirect Invocation
const context = { value1: 'A', value2: 'B' };
function indirectInvocation() { console.log(this);}
indirectInvocation.call(context);
indirectInvocation.apply(context);
// Constructor Invocation
function constructorInvocation() { console.log(this);}
new constructorInvocation();
This i That
(function () {
"use strict";
document.addEventListener("DOMContentLoaded", function () {
var colours = ["red", "green", "blue"];
document.getElementById("header")
.addEventListener("click", function () {
// this és una referència al clicat
var that = this;
colours.forEach(function (element, index) {
console.log(this, that, index, element);
// this és undefined
// that és el que s'ha clicat
}); }); }); })();
This i funcions fletxa
function UiComponent() {
var _this = this;
var button = document.getElementById('myButton');
button.addEventListener('click', function () {
console.log('CLICK');
_this.handleClick();
});
}
UiComponent.prototype.handleClick = function () {
···
};
function UiComponent() {
var button = document.getElementById('myButton');
button.addEventListener('click', () => {
console.log('CLICK');
this.handleClick(); // (A)
});
}
This i funcions fletxa
https://blog.bitsrc.io/arrow-functions-vs-regular-functions-in-javascript-458ccd863bc1
var variable = "Global Level Variable";
let myObject = {
variable: "Object Level Variable",
arrowFunction: () => {
console.log(this.variable);
},
regularFunction() {
console.log(this.variable);
}
};
myObject.arrowFunction();
myObject.regularFunction();
function Car(type, fuelType){
this.type = type;
this.fuelType = fuelType;
}
function setBrand(brand){
Car.call(this, "convertible", "petrol");
this.brand = brand;
console.log(`Car details = `, this);
}
const newBrand = new setBrand('Brand1');
this.x = 9;
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9
var boundGetX = getX.bind(module);
boundGetX(); // 81
DOM
DOM : Window
DOM: Trobar els nodes
No recomanable per a nous nodes ja que força a remapejar el DOM
elementsQuery.parentNode.removeChild(elementsQuery);
// Per a esborrar cal cridar al node pare
DOM: Estils
Tècniques per crear elements: Template Literal
function generateGraphCard(graph){
let cardTemplate = document.createElement('div');
cardTemplate.classList.add('col');
cardTemplate.innerHTML = `<div class="card"><div class="card-header">${graph.title}</div>
<div class="card-body">
<div class="graph"></div>
<p class="card-text">${graph.description}</p>
<a href="#/graph/${graph.id}" class="btn btn-primary">Full screen</a>
</div>
</div>`;
let graphContainer = cardTemplate.querySelector('.graph');
graphContainer.append(graph.Data ? generateBarGraph(graph.Data) : graphPlaceholder());
graphContainer.classList.add()
return cardTemplate;
}
Tècniques per crear elements: Interpolacions i Wrapper
function renderNews(news){
let newsTemplate = `
<article id="article_{{id}}">
<a href="{{link}}"><h2>{{headline}}</h2></a>
<time>{{date}}</time><address>{{authors}}</address>
<p>{{short_description}}</p>
<p>{{category}}</p>
</article>
`;
return wrapElement(applyInterpolations(newsTemplate,news));
}
function extractInterpolations(template){
let regex = /\{\{([^\{\}]*)\}\}/g;
return [...template.matchAll(regex)];
}
function applyInterpolations(template,data){
return extractInterpolations(template)
.reduce((T,[I,att]) =>
T = T.replace(I,data[att])
,template);
}
function wrapElement(innerHTML){
let wrapper = document.createElement('div');
wrapper.innerHTML = innerHTML;
return wrapper.firstElementChild;
}
Esperar a que carregue el DOM
(function () {
"use strict";
document.addEventListener("DOMContentLoaded", function () {
for (let i = 0; i < 100; i++) {
let contenidor = document.getElementById("content");
let numero = document.createElement("p");
numero.innerHTML = i;
contenidor.appendChild(numero);
}
});
})();
També podem posar el script al final del body.
<article
id="electriccars"
data-columns="3"
data-index-number="12314"
data-parent="cars">
...
</article>
Formularis
Formularis
Cicle tradicional del formulari
Cicle del formulari amb Javascript
Esdeveniments en formularis
<form onsubmit="return validar();">
<form onsubmit="this.disabled=true">
let elemento=document.getElementById("formulario");
elemento.submit();
Expressions regulars
function validate()
{
var phoneNumber = document.getElementById('phone-number').value;
var phoneRGEX = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/;
var phoneResult = phoneRGEX.test(phoneNumber);
alert("phone:"+phoneResult );
}
Esdeveniments
Events & Handlers
Events en línia
<p onmouseover="this.style.background='#FF0000';" onmouseout="this.style.background='#FFFFFF';">HOLA</p>
Registre d’esdeveniments tradicional
window.onload = function () {
document.getElementById('hola').onmouseover = function () { this.style.background = '#FF0000';};
document.getElementById('hola').onmouseout = function () { this.style.background = '#FFFFFF';};
}
Registre d’esdeveniments avançat
W3C
(function () {
"use strict";
document.addEventListener("DOMContentLoaded", function () {
document.getElementById('hola').addEventListener('mouseover',function () { this.style.background = '#FF0000';} ,false);
document.getElementById('hola').addEventListener('mouseout',function () { this.style.background = '#FFFFFF';} ,false);
});
})();
Treure informació del Event
(function () {
"use strict";
document.addEventListener("DOMContentLoaded", function () {
document.getElementById('hola').addEventListener('mouseover',manejador,false);
document.getElementById('hola').addEventListener('mouseout',manejador,false);
});
})();
function manejador(e){
console.log(e.type, e.target);
if (e.type == 'mouseover') {this.style.background = '#FF0000'; } // Quí és this?
if (e.type == 'mouseout') {this.style.background = '#FFFFFF'; }
if (e.target.id == 'hola' ) {console.log('Hola');}
}
document.querySelector("table").addEventListener("click", (event) =>
{
if (event.target.nodeName == 'TD')
event.target.style.background = "rgb(230, 226, 40)";
}
);
Events de teclat
Un Event de teclat genera un KeyboardEvent.
Per saber la tecla, s’ha d’utilitzar .code
Els codis poden ser: https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_code_values
Iteradors
Iterables
let iterator = someString[Symbol.iterator]();
iterator.next();
iterator.next();
iterator.next();
let myIterable = {};
myIterable[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};
[...myIterable]; // [1, 2, 3]
Funció generadora
Iteradors (ES6)
let iterable = [10, 20, 30];
for (let value of iterable) { value += 1; console.log(value);}
function f(x, y, z) { }
var args = [0, 1, 2];
f(...args);
var parts = ['shoulder', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];
Recorrer iterables
let a = [1,2,3,4,5];
a.forEach(element => { console.log(element);});
b = a.map(function(item){return item**2;});
console.log(b);
console.log(a.filter(function(item){return item%2 == 0;}));
var total = a.reduce(function (previous, current) {
console.log(previous,current);
return previous + current;
}, 0);
console.log(total);
querySelector retorna un NodeList (objecte) que conté el seu forEarch
Array.from()
let arrayLike = { // tiene índices y longitud => array-like� 0: "Hola",� 1: "Mundo",� length: 2�};�let arr = Array.from(arrayLike);
Map()
Comparativa
| Maps | Objectes | Sets | Arrays |
Recorrer | Si | No | Si | Si |
Repetits | Valors si | Els valors si | No | Si |
Clau-valor | Objectes com a clau | Si | El valor és la clau | La clau és l’índex |
Esborrar | .delete() | delete | .delete() | No dirèctament |
Flltrar, ordenar, map | No | No | No | Si |
Accés aleatori | Si | Si | No | Si |
Mòduls
Coses que no són mòduls (Espais de noms)
// namespace, not module
var Utils = {
cancelEvt(evt) {
evt.preventDefault(); evt.stopPropagation(); evt.stopImmediatePropagation();
},
wait(ms) {
return new Promise(function c(res){ setTimeout(res,ms); });
},
isValidEmail(email) {
return /[^@]+@[^@.]+\.[^@.]+/.test(email);
}
};
Coses que no són mòduls (Estructures de dades)
// data structure, not module
var Student = {
records: [{ id: 14, name: "Kyle", grade: 86 }, { id: 73, name: "Suzy", grade: 87 }, { id: 112, name: "Frank", grade: 75 }, { id: 6, name: "Sarah", grade: 91 }],
getName(studentID) {
var student = this.records.find(student => student.id == studentID);
return student.name;
}
};
Student.getName(73);
// Suzy
Mòduls abans de ES6
Mòduls manuals (Amb estat i control d’accés)
function defineStudent() {
var records = [{ id: 14, name: "Kyle", grade: 86 }, { id: 73, name: "Suzy", grade: 87 }, { id: 112, name: "Frank", grade: 75 }, { id: 6, name: "Sarah", grade: 91 }];
var publicAPI = {getName};
return publicAPI;
function getName(studentID) {
var student = records.find(student => student.id == studentID);
return student.name;
}
}
var fullTime = defineStudent();
fullTime.getName(73); // Suzy
Mòduls ES6
export { getName };
var records = [{ id: 14, name: "Kyle", grade: 86 }, { id: 73, name: "Suzy", grade: 87 }, { id: 112, name: "Frank", grade: 75 },{ id: 6, name: "Sarah", grade: 91 }];
function getName(studentID) {
var student = records.find(
student => student.id == studentID
);
return student.name;
export function getName(studentID) {}
export default function getName(studentID) {
import { getName } from "/path/to/students.js";
// getName(73);
import { getName as getStudentName } from "/path/to/students.js";
import getName from "/path/to/students.js"; // Si getname és default
import { default as getName, /* .. others .. */ } from "/path/to/students.js";
import * as Student from "/path/to/students.js";
// Student.getName(73);
<script> amb mòduls
<script type="module" src="functions.js"></script>
<script type="module" src="script.js"></script>