Note that there are some explanatory texts on larger screens.

plurals
  1. POjavascript OOP syntax, and object that is both a var and a function
    primarykey
    data
    text
    <p>This is related to a question I asked previously here: <a href="https://stackoverflow.com/questions/7354760/how-to-implement-chained-method-calls-like-jquery">How to implement chained method calls like jQuery?</a></p> <p>I have been using the method from the check answer from some time there, and it works well. But I would like to alter the syntax for my toolkit even further.</p> <ol> <li><p><code>foo(firstarg).bar(secondarg); // should function as the question above.</code></p></li> <li><p><code>foo(onlyarg).bar // a function with one argument</code></p></li> <li><p><code>foo.bar(onlyarg); // should also work, when a first argument is not appropriate.</code></p></li> <li><p><code>foo.bar; // a function without an argument, or returns a static value.</code></p></li> </ol> <p>I would like all 4 syntaxs to work off the same foo object, but lack the OOP understanding to do so. I have tried a few things, and so far I can get 1 &amp; 2 to work, and 3 &amp; 4 to work, but not to all work together. It also would be nice if chaining remained an option by having each function return the root object.</p> <p>Edit: I clearly need to be more specific, here is what I have now:</p> <pre><code> var main = function(obj){ this.obj = obj; }; var tool = function(obj){ return new main(obj); }; main.prototype = { alertThisPlus : function(plus){ alert(this.obj + ' ' + plus); }, alertJustThis : function(){ return alert(this.obj); } }; </code></pre> <p>usage</p> <pre><code> tool('hello').alertThisPlus('world'); // returns alert('hello world') tool().alertJustThis('hello world'); // returns alert('hello world'); </code></pre> <p>what I would like is to do this:</p> <pre><code> tool('hello').alertThisPlus('world'); // returns alert('hello world') no change tool.alertJustThis('hello world'); // returns alert('hello world') does not work </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload