Skip to content

Instantly share code, notes, and snippets.

@DavidPeralvarez

DavidPeralvarez/index.html Secret

Created Apr 2, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.