Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is my usual approach:</p> <pre><code>MyClass = function(x, y, z) { // This is the constructor. When you use it with "new MyClass()," // then "this" refers to the new object being constructed. So you can // assign member variables to it. this.x = x; ... }; MyClass.prototype = { doSomething: function() { // Here we can use the member variable that // we created in the constructor. return this.x; }, somethingElse: function(a) { } }; var myObj = new MyClass(1,2,3); alert(myObj.doSomething()); // this will return the object's "x" member alert(myObj.x); // this will do the same, by accessing the member directly </code></pre> <p>Normally the "this" keyword, when used in one of the object's methods, will refer to the object itself. When you use it in the constructor, it will refer to the new object that's being created. So in the above example, both alert statements will display "1".</p> <hr> <p>An exception to this rule is when you pass one of your member functions somewhere else, and then call it. For example,</p> <pre><code>myDiv.onclick = myObj.doSomething; </code></pre> <p>In this case, JavaScript ignores the fact that "doSomething" belongs to "myObj". As a result, the "this" inside doSomething will point to another object, so the method won't work as expected. To get around this, you need to specify the object to which "this" should refer. You can do so with JavaScript's "call" function:</p> <pre><code>myDiv.onclick = function() { myObj.doSomething.call(myObj); } </code></pre> <p>It's weird, but you'll get used to it eventually. The bottom line is that, when passing around methods, you also need to pass around the object that they should be called on.</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.
    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