Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
How to refer to a state for a javascript function without refering to its name explicitely

How can I set state https://jsfiddle.net/7q1530sp/10/ doesn't work

function o(){
 this.state = true;
}

o.f = function() {
  alert(this.state);
}
o.state = false;
o();
o.f();

instead of refering to o explicitely within its function https://jsfiddle.net/7q1530sp/9/

function o(){
 o.state = true;
}

o.f = function() {
  alert(this.state);
}
o.state = false;
o();
o.f();

Is there a way to refer to o without using its name ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Usually, to initialize a function you should use NEW before executing it, example:

var my = new fn()

However, I would advise you to opt for prototypes:

In addition to being comfortable to use, in case of complex projects, they will also allow you to divide your project into multiple files while keeping the code clean and tidy!

I leave you a small example on how prototypes are used:

var my = function(){}
my.prototype.test = true;
my.prototype.run = function(){
    console.log(this.test)
}

var w = new my();
w.run();
w.test = false;
w.run();

Update: Of course, you could also globally change the value of the variable like so:

var my = function(){}
my.prototype.test = true;
my.prototype.run = function(){
    console.log(this.test)
}

new my().run();
my.prototype.test = false;
new my().run();

Output:

true
false
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda