Read about Scopes in JavaScript, for example, in Java Script: The Good Parts.
In Java Script, there is only a scope inside functions. If you specify a variable inside a function using var , you cannot access it from outside this function. This is a way to make private variables in JavaScript.
You can use the this variable, which points to the current object you are in (this is not the area itself). But! if you initiate a function without a new command, than , this will point to the outer region (in most cases this is a window = global region object).
Example:
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(); //ba == 10 var b = bar(); //ba == undefined, but a in global scope
Btw, check the syntax of the apply Mozilla docs / apply method. So you can see that the fist argument is the object that will be this when your method is called.
So, consider this example:
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();
Maybe better to do
var that = this;
before calling the apply method, but maybe it is not needed. not sure
So this will definitely work:
function foo(){ console.log(this.a); } jQuery.extend({ somefunc: function(func){ this.a = 10; func.apply(this); } }); $.somefunc(foo);
source share