Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Read about Scopes in JavaScript for example in "Java Script: The good parts".</p> <p>In the Java Script there is only scope inside Functions. If you specify your variable inside function with <strong>var</strong> you can't access them from outside of this function. This is way to make private variables in JavaScript.</p> <p>You can use <strong>this</strong> variable, that point to current object you are in (this is not a scope itself). But! if you initiate function without <strong>new</strong> command, than <strong>this</strong> will point to outer scope (in most cases it's window object = global scope).</p> <p>Example:</p> <pre><code>function foo(){ var a = 10; } var f = foo(); //there is nothing in f var f = new foo(); //there is nothing in f function bar(){ this.a = 10; } var b = new bar(); //b.a == 10 var b = bar(); //b.a == undefined, but a in global scope </code></pre> <p>Btw, check out syntax of apply method <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply" rel="nofollow noreferrer">Mozilla docs/apply</a> So you can see, that fist argument is object, that will be <strong>this</strong> when your method will be called.</p> <p>So consider this example:</p> <pre><code>function bar(){ console.log(this.a); console.log(this.innerMethod(10)); } function foo(){ this.a = 10; this.innerMethod = function(a){ return a+10; } bar.apply(this); } var f = new foo(); // =&gt; you will get 10 and 20 in the console. var f = foo(); // =&gt; you will still get 10 and 20 in the console. But in this case, your "this" variable //will be just a global object (window) </code></pre> <p>Maybe it's better to make </p> <pre><code>var that = this; </code></pre> <p>before calling apply method, but maybe it's not needed. not sure</p> <p>So, this definitely will work:</p> <pre><code>function foo(){ console.log(this.a); } jQuery.extend({ somefunc: function(func){ this.a = 10; func.apply(this); } }); $.somefunc(foo); //will print 10. </code></pre>
    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.
    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