Skip to content

Instantly share code, notes, and snippets.

@DavidPeralvarez
Created April 2, 2020 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidPeralvarez/4e34ed510c6f4ebfdb195d4c50ad5e02 to your computer and use it in GitHub Desktop.
Save DavidPeralvarez/4e34ed510c6f4ebfdb195d4c50ad5e02 to your computer and use it in GitHub Desktop.
JavaScript - Operadores Typeof e Instanceof
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Curso de Javascript</title>
</head>
<body>
<script src="scripts.js"></script>
</body>
</html>
// typeof = devuelve cadena indicando el tipo
var fn = function(){
};
var txt = '';
var num = 1;
var obj = {};
var bool = true;
function devuelveTipo( a ){
return typeof a;
}
console.log( devuelveTipo( fn ) );
console.log( devuelveTipo( txt ) );
console.log( devuelveTipo( num ) );
console.log( devuelveTipo( obj ) );
console.log( devuelveTipo( bool ) );
if( typeof txt === 'boolean' ) {
console.log( 'soy una string' );
}
// instanceof = verificar el tipo de un objeto
var Coche = function(){
this.color = 'Rojo';
}
var Moto = function(){
this.color = 'Verde';
}
var coche1 = new Coche();
var moto1 = new Moto();
function verificarTipo( a ){
if( a instanceof Coche ) {
return 'soy del tipo coche';
} else if ( a instanceof Moto ) {
return 'soy del tipo moto';
} else {
return false;
}
}
console.log( verificarTipo( coche1 ) );
console.log( verificarTipo( moto1 ) );
console.log( verificarTipo( {} ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment