Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>No, you can't. That's just the way to do it. Btw, you can easily <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind#Compatibility" rel="nofollow">shim the <code>bind</code> method</a> so that it is available in older browsers, too.</p> <p>An alternative would be to move the closure into the prototype method, if you know that you always will need to bind the actual function:</p> <pre><code>TestObj.prototype.getCallMeLaterTestObj = function () { var that = this; return function() { console.log('I am ' + that.constructor.name + ' my value is ' + that._value); }; }; setTimeout(v.getCallMeLaterTestObj(), 10); </code></pre> <p>Btw, your prototype has no <code>constructor</code> property so the log will not work as expected.</p> <p>Your only chance is to avoid the <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this" rel="nofollow"><code>this</code> keyword</a> entirely:</p> <pre><code>TestObj = function() { var privateVar = false; // these are private static function TestObj(value) { function giveMe() { return value; } function callMeLaterTestObj() { console.log('I am TestObj my value is ' + giveMe()); } this._value = value; this.giveMe = giveMe; this.callMeLaterTestObj = callMeLaterTestObj; /* you could do this as well: return { _value: value, giveMe: giveMe, callMeLaterTestObj: callMeLaterTestObj }; */ } return TestObj; })(); var v = new TestObj; setTimeout(v.callMeLater, 10); </code></pre> <p>But this is not very memory-efficient, as it does not use prototypical inheritance at all.</p>
 

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