Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>No, you can't really; not the way you're creating objects at least.</p> <p>You can sort of do this, by enumerating all the functions on the object and binding them to the object itself. Something like this:</p> <pre><code>Object.keys(obj) .filter(function(n) { return typeof obj[n] == "function" }) .forEach(function(n) { obj[n] = obj[n].bind(obj) }) </code></pre> <p>This function will go over the public, enumerable properties of <code>obj</code> and make sure that any functions on it are bound to <code>obj</code>; i.e. <code>this</code> is now bound to <code>obj</code>.</p> <hr> <h2>A primer on <code>this</code></h2> <p>When you call new, <code>this</code> within the constructor gets bound to the newly created object. If you do need a reference to <code>this</code> as it was bound at constructor time, you do need to keep away a reference to it.</p> <p>Functions in JavaScript are bound to wherever it is called. Here's an example:</p> <pre><code>var foo = new function() { this.bar = function() { return 'bar' } this.baz = function() { return this.bar() } } console.log(foo.bar()) // bar console.log(foo.baz()) // bar var bar = function() { return "window" } var baz = foo.baz console.log(baz()) // window </code></pre> <p>When we call <code>foo.baz()</code> it'll look to <code>foo</code> for the implementation of <code>bar</code>, but when calling <code>foo.baz</code> through a "detached" reference, it'll look to whatever the global object is (in this case the browser window object) and call <code>bar</code> from there. Because we defined <code>bar</code> in the global context, it then returns <code>window</code>.</p> <p>The practice of assign a variable called <code>self</code> is so that it doesn't matter how you call your methods, because you always reference the <code>this</code> at the time of creation through the <code>self</code> variable. You don't have to write things this way, but then you should understand that references to <code>this</code> may change under your feet.</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. VO
      singulars
      1. This table or related slice is empty.
    2. 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