Note that there are some explanatory texts on larger screens.

plurals
  1. POPreserving a reference to "this" in JavaScript prototype functions
    primarykey
    data
    text
    <p>I'm just getting into using prototypal JavaScript and I'm having trouble figuring out how to preserve a <code>this</code> reference to the main object from inside a prototype function when the scope changes. Let me illustrate what I mean (I'm using jQuery here):</p> <pre><code>MyClass = function() { this.element = $('#element'); this.myValue = 'something'; // some more code } MyClass.prototype.myfunc = function() { // at this point, "this" refers to the instance of MyClass this.element.click(function() { // at this point, "this" refers to the DOM element // but what if I want to access the original "this.myValue"? }); } new MyClass(); </code></pre> <p>I know that I can preserve a reference to the main object by doing this at the beginning of <code>myfunc</code>:</p> <pre><code>var myThis = this; </code></pre> <p>and then using <code>myThis.myValue</code> to access the main object's property. But what happens when I have a whole bunch of prototype functions on <code>MyClass</code>? Do I have to save the reference to <code>this</code> at the beginning of each one? Seems like there should be a cleaner way. And what about a situation like this:</p> <pre><code>MyClass = function() { this.elements $('.elements'); this.myValue = 'something'; this.elements.each(this.doSomething); } MyClass.prototype.doSomething = function() { // operate on the element } new MyClass(); </code></pre> <p>In that case, I can't create a reference to the main object with <code>var myThis = this;</code> because even the original value of <code>this</code> within the context of <code>doSomething</code> is a <code>jQuery</code> object and not a <code>MyClass</code> object.</p> <p>It's been suggested to me to use a global variable to hold the reference to the original <code>this</code>, but that seems like a really bad idea to me. I don't want to pollute the global namespace and that seems like it would prevent me from instantiating two different <code>MyClass</code> objects without them interfering with each other.</p> <p>Any suggestions? Is there a clean way to do what I'm after? Or is my entire design pattern flawed?</p>
    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.
    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