Pergunta

Considerando o seguinte exemplo JavaScript:

var myobj = {   func1: function() { alert(name in this) },
                func2: function() { alert(name in this) },
                func3: function() { alert(name in this) }
}

myobj.func2(); // returns true
myobj.func4(); // undefined function

É possível criar uma chave 'Catch-all' para myobj Isso será chamado se não houver chave/função definida (como em func4()) ao reter o myobj.functionCall() formato?

Foi útil?

Solução

Você está procurando __noSuchMethod__:
JavaScript Getter para todas as propriedades

Outras dicas

Você pode criar um objeto JavaScript com teclas 'curinga' ou 'catch-all' usando um proxy e uma função getter. Ao contrário das soluções fornecidas, um proxy deve funcionar em praticamente qualquer ambiente, incluindo node.js

var foo = new Object()

var specialFoo = new Proxy(foo, {
    get(target,name) {
        // do something here
        return name
    }
})

console.log(specialFoo.blabla) // this will output "blabla"

Se você deseja que as propriedades sejam chamáveis, basta retornar uma função:

var specialFoo = new Proxy(foo, {
    get(target,name) {
        return function() {
            console.log('derp')
            return name
        }
    }
})


specialFoo.callMe() // this will print derp

Detalhes: Documentação sobre Mozilla

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top