Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript closure and "this"
    text
    copied!<p>My question is... in CallMeLaterTestObj function in the TestObj the "this" is the window object and not TestObj. How can I restructure this so that within the CallMeLater function I don't have to wrap the call <code>function() { v.CallMeLaterTestObj(); }</code> in a closure or using the bind function since it has limited support to newer browsers. Two objectives:</p> <ul> <li>Keeping "this" in function calls within the object</li> <li><p>Maintaining a separate value for "value" for each separate object so they don't share the same value.</p> <p>// Emulating public api, private methods, private variables, public fields. </p> <p>// New portion of question</p></li> <li><p>Re-written to include binding function and prototypical notation. How do you move the Binding function into a base object that all new objects would get?</p></li> <li><p>This is as close as I can come to getting this to use the best of both worlds. I have no idea what the pitfalls of this approach are though</p> <pre><code> var BaseObject = function () { _getBinding = function (method) { var _self = this; return function () { _self[method].apply(_self, arguments); }; }; return { CallInline: _getBinding } }(); var TestObj = function (value) { $.extend(this, BaseObject); // public var this._value = value; }; TestObj.prototype = function() { var privateVar = false; // these are private _giveMe = function () { return this._value; }, _callMeLaterTestObj = function () { console.log('I am ' + this.constructor.name + ' my value is ' + this._value); }; // public API return { GiveMe : _giveMe, CallMeLaterTestObj : _callMeLaterTestObj } }(); function CallMeLater(v, i) { setTimeout(v.CallInline('CallMeLaterTestObj'), 10); } var V1 = new TestObj(1); var V2 = new TestObj(2); var V3 = new TestObj(3); console.log('V1= ' + V1.GiveMe()); console.log('V2= ' + V2.GiveMe()); console.log('V3= ' + V3.GiveMe()); console.log('---'); V1.CallMeLaterTestObj(); console.log('---'); </code></pre></li> </ul>
 

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