Last active
December 30, 2015 07:39
-
-
Save hernan604/7797742 to your computer and use it in GitHub Desktop.
js call and apply examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var pessoas = [ | |
{ | |
"nome" : "João", | |
"sobrenome" : "Silva" | |
}, | |
{ | |
"nome" : "Mary", | |
"sobrenome" : "Mafra" | |
}, | |
]; | |
var carros = [ | |
{ | |
"marca" : "Ferrari", | |
"modelo": "Testarrossa" | |
}, | |
{ | |
"marca" : "Fiat", | |
"modelo": "Uno" | |
}, | |
]; | |
function executar_via_call( args_array ) { | |
console.log( this ); | |
console.log( args_array ); | |
} | |
function executar_via_apply( arg1, arg2 ) { | |
console.log( this ); | |
console.log( arg1 ); | |
console.log( arg2 ); | |
} | |
console.log( "obj pessoas - Executando chamada via call" ); | |
for ( var i in pessoas ) { | |
var pessoa = pessoas[ i ]; | |
executar_via_call.call( pessoas[ i ], "valor1", "valor2" ); | |
} | |
console.log( "obj pessoas - Executando chamada via apply" ); | |
for ( var i in pessoas ) { | |
var pessoa = pessoas[ i ]; | |
executar_via_apply.apply( pessoas[ i ], [ "valor1", "valor2" ] ); | |
} | |
console.log( "obj carros - Executando chamada via call" ); | |
for ( var i in carros ) { | |
var carro = carros[ i ]; | |
executar_via_call.call( carro, "valor1", "valor2" ); | |
} | |
console.log( "obj carros - Executando chamada via apply" ); | |
for ( var i in carros ) { | |
var carro = carros[ i ]; | |
executar_via_apply.apply( carro, [ "valor1", "valor2" ] ); | |
} | |
//------------------------------------------------------------------- | |
function ajax_req( some_url, callback ) { | |
var response = { color : "mixed-coloors" }; | |
callback && callback( response ); | |
} | |
function Person( args ) { | |
this.id = args.id; | |
this.name = args.name; | |
this.age = args.age; | |
}; | |
Person.prototype.get_color = function( callback ) { | |
var self = this; | |
ajax_req( "/pessoa/" + this.id , function( data ) { | |
callback && callback.call( self, data.color ); | |
} ); | |
}; | |
var person = new Person( { id: 1, name : 'joe curry', age : 20 } ); | |
person.get_color( | |
function( color ) { | |
this.color = color; | |
alert( 'The color of ' + this.name + ' is ' + this.color ); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment