Please have a look at this:
foo = function() {
document.write("Unicorn <br>");
return this; //This should return the foo Object every single time
};
//Now when I run foo(), it should display "Unicorn" and it does
foo();
foo.bake = function() {
document.write("Baked! <br>");
};
foo.bake();
foo.prototype.bake = foo.bake;
foo().bake();
The first time I run foo(), it writes out “Unicorn” as expected. Then I added new method into the existing foo Object (method bake() which writes out “Baked!”, and it works, too. Then I tried to added the same method, but this time, using .prototype, and IF I understand it correctly, now foo().bake should be the same function as foo.bake.
I’ve searched many articles on StackOverflow about how jQuery could behave as an Object and Function at the same time. I read and understood the answers given but they did not solve my problem.
My question: How could I make foo().bake() work the same as foo.bake(). Is it possible?
Thanks everyone in advanced._
That’s not the correct way to use constructor and the instance.
In fact, you don’t have to return anything in your constructor, the only thing you need to do is to use the
newkeyword.So in your case, modified the last statement to:
(new foo()).bake();