0

This is a tough one to word, but how can you have Model.method() and Model() be valid at the same time? The particular library that makes me ask this is mongoose (http://mongoosejs.com/docs/) where Model as an object represents a mongo collection and has several methods and Model as a function is a constructor for a mongo document with some methods. I'm trying to do something similar, but it just returns a function making typeof Model === 'function' and never object. It is as follows:

let model = (function(){
        for(var i in queries){
            if(typeof i == 'function'){
                if(i == 'insert'){
                    continue;
                }
                this[i] = function(){
                    queries[i].apply(this, arguments); // queries is a separate module I've written that has methods for querying a DB
                };
            }
        }
        return (function(){
            for(var i in arguments[0]){
                if(!(i in schema) && typeof arguments[0][i] != typeof schema[i]){
                    this[i] = arguments[0][i];
                }
                else{
                    throw new Error('Invalid argument, key: ' + i + ' value: ' + arguments[0][i]);
                }
            }
            for(var i in schema.methods){
                this[i] = schema.methods[i];
            }
        });
    })();
2
  • "How can a javascript object also be a function?" It's more the other way around, JavaScript functions are objects (always). Commented Sep 30, 2015 at 14:34
  • That said, I don't see any particular properties being put on the function that ends up assigned to model. The fact it's an object isn't really being used (other than that we can have a reference to it) in the quoted code. Commented Sep 30, 2015 at 14:36

2 Answers 2

5

All JavaScript functions are objects. That's just how JavaScript works.

function alert(message) {
    document.body.appendChild(document.createTextNode(message));
    document.body.appendChild(document.createElement('br'));
}

function myFunction() {
  alert("This is myFunction");
}

myFunction.property = "Hello";

myFunction.recursive = myFunction;

myFunction();
alert(myFunction.property);
alert(myFunction.name);
myFunction.recursive.recursive.recursive.recursive.recursive();

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

Comments

0

JavaScript functions are a special kind of JavaScript objects. That means that all the functions are objects, but objects are not necessarily functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.