0

I my case, I have a class, say

var Validator = function (...) {
    ...
};
Validator.prototype.validate = function(){...}

Now as the validate function is so important, I want to change the usage validator.validate(...) into validator(...), here validator is an instance of Validator.
Is it possible and how to make it?

3
  • what is the problem with using validator.validate(…) ..? Commented Jun 29, 2015 at 4:11
  • Currently, it's not possible to define a custom type so its instances are callable. The language standard has specified that it should be supported, but engines haven't yet implemented it. Commented Jun 29, 2015 at 4:11
  • Try this, jsfiddle.net/snlacks/jxnhqm64/1 That other answer is okay, but I address a potential name/memory issue. Commented Jun 29, 2015 at 4:22

1 Answer 1

0

You could create a reference to your instance method:

var validate = yourValidatorInstance.validate;

Hope this helps

Sign up to request clarification or add additional context in comments.

4 Comments

You would have to bind the context: var validate = yourValidatorInstance.validate.bind(yourValidatorInstance);.
Yes right, lexical this would not be the same but I see no problem with using bind?
To make things simpler: var validate = rebind(yourValidatorInstance, "validate"); function rebind(obj, name) { return obj[name].bind(obj); }.
Yes I like this approach using underscore/lodash u could also use _.bind

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.