Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Minha dúvida é de um mero iniciante em javascript/jquery.
Já li vários artigos sobre o assunto e acho que peguei o conceito, mas porque nesse exemplo que vou postar, de um jeito ele pega o valor de this e no outro não?
Show de bola a explicação, agora sim consegui compreender melhor esse assunto.
Demo:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<a href="#" class="ativar">Click aqui</a>
<br />
<a href="#" onclick="faleOi();">Click aqui xD</a>
<br />
<a href="#" class="outraClass" >Clique aqui de novo</a>
<div class="caixaDeList">
<ul>
<li></li>
<li></li>
</ul>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script type="text/javascript">
function faleOi(){
alert('Oi Pessoa!');
}
$(document).ready(function() {
$('.ativar').click(function(){
var valorThis = $(this).html();
alert(valorThis);
});
//Ao invez de usar uma função anonima $( "#btn-action" ).bind( "click", function() { /*Anon*/ });
//Utilizei uma já existente ^^
$('.outraClass').click(faleOi);
});
$( ".caixaDeList ul li" ).each(function() {
var vm = this;
//verificar
$.ajax({
url: 'index.html'
,data: {nome: 'Gabriel'}
,type:'POST'
,dataType: 'json'
,success: function(json){
var vm = this;
//Nesse momento o escopo do this é da propria função, vamos imprimir pra ver...
console.log(this);
return true;
}
,error: function(json){
}
});
});
</script>
</body>
</html>
Caso quiser manipular o 'this' da listagem acima você pode guardar numa variavel no escopo acima....
Você pode fazer algo como:
$( ".caixaDeList ul li" ).each(function() {
var vm = this;
//verificar
$.ajax({
url: 'index.html'
,data: {nome: 'Gabriel'}
,type:'POST'
,dataType: 'json'
,success: function(json){
console.log(vm); //equivalente ao dom do loop xD
[https://github.com/gabrieldarezzo/helpjs-ravi](https://github.com/gabrieldarezzo/helpjs-ravi)R
$( ".caixaDeList ul li" ).each(function() {
var vm = this;
//verificar
$.ajax({
url: 'index.html'
,data: {nome: 'Gabriel'}
,type:'POST'
,dataType: 'json'
,success: function(json){
console.log(vm); //equivalente ao dom do loop xD
Recomendo a leitura:
[https://github.com/gabrieldarezzo/helpjs-ravi](https://github.com/gabrieldarezzo/helpjs-ravi)
Outro link legal:
[http://blog.da2k.com.br/2015/01/30/javascript-como-invocar-funcoes/](http://blog.da2k.com.br/2015/01/30/javascript-como-invocar-funcoes/)Boa Gabriel, muito bom o conteúdo.
Consegui abrir bem a mente.
Acrescentando, para entendermos melhor, vamos ver alguns uso do this apenas com javascript
function Aluno()
{
this.nome = 'João';
this.ra = '';
var idade = 12;
this.exibeNome = function()
{
return this.nome;
}
this.cadastraRA = function(ra)
{
this.ra = ra;
return this;
}
this.exibeRA = function()
{
return this.ra;
}
this.responderChamada = function()
{
chamada = new Chamada();
return chamada.marcaPresenca(this);
}
}
function Chamada() this.marcaPresenca = function(aluno)
{
return aluno.nome + " presente!";
}
}
joao = new Aluno();
console.log(joao.cadastraRA(1234).exibeNome()); // Exibira: Joãoconsole.log(joao.responderChamada()); // Exibira: João presente!
/* Como foi passado o this em marcaPresenca(), o objeto "Chamada" tem acesso aos metodos
e propriedades publicas de Aluno */
console.log(joao.idade); // Exibira: undefined
console.log(joao.ra); // exibira: 1234Entendi EdCesar, show de bola... Consegui entender bem agora o uso do this xD