Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The problem probably lies in the <code>this</code> keyword in <code>drawFrame</code>. When the <code>setTimeout</code> fires, <code>this</code> in side is no longer <code>rect</code>.</p> <p>The solution is using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" rel="nofollow">apply</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" rel="nofollow">call</a>. <code>f.apply(self)</code> bind the <code>this</code> keyword in function <code>f</code> to the first argument <code>f</code>.</p> <p>So change this way:</p> <pre><code>rectangle.prototype.drawFrame = function draw(){ var self = this; this.opacity += 0.005; this.renderSelf(); if (this.opacity &lt; 1) { requestAnimationFrame(function(){ draw.call(self) }); } }; </code></pre> <p>check out this JSBin. <a href="http://jsbin.com/OwaHALUF/4/edit" rel="nofollow">http://jsbin.com/OwaHALUF/4/edit</a></p> <p>========================</p> <p>edited upon a valid comment:</p> <ul> <li><code>x</code> in the original code is not semantic and misses <code>var</code> declaration. Fixed.</li> <li>prefer <code>requestAnimationFrame</code> to <code>setTimeout</code></li> <li>stop call <code>drawFrame</code> if opacity >= 1 (useful if requestAnimationFrame is not availlable)</li> <li>prefer named function expression over re-assignment. It reduces closure overhead.(This overhead may be not neglected if the animation lasts long enough). And more concise code is bonus.</li> </ul>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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