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

128
Visualizações
How to create a getter and setter for jquery object?

I want to add a getter and a setter for the $ object, similar to the val() function for a DOM object.

If the val is called without parameters, the getter is invoked. With one parameter, the setter is invoked.

I have tried with

$.fn.simpleSearch = function() {
    return _variable;
}

$.fn.simpleSearch = function (search) {
    _variable = search;
}

But it does not work.

Any hint?

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

0

You cannot define $.fn.simpleSearch twice. The 2nd definition will override the first.

You can set up a simple getter and setter like this:

$.fn.simpleSearch = function (search) {
    if ( typeof search != 'undefined' ) {
        _variable = search;
    }
    return _variable;
}

console.log( $(jQuery).simpleSearch() )
console.log( $(jQuery).simpleSearch('foo') )

However, this code is not complete because _variable needs to be defined somewhere. Do you intend it to be a global variable? A property of an object?

Also see How to create custom JQuery function and how to use it?

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