javascript - Pass in jQuery/plainJS variables/functions of a current scope to anonymous function called from current scope -
How to pass the current scope variable and functions of an anonymous function in plain JavaScript or jQuery (if it is specific to the framework) .
For example:
jQuery.extend ({someFunction: function (onSomeEvent) {var variable = 'some text' onSomeEvent.apply (this); // how Please pass the current scope variable / function in this function? Return tap; _someMethod (arg) {console.log (arg);}}});
Everything from firebug should be logged in with the above function:
jQuery.someFunction (function () {console.log (this.variable) ; // or console.log (variable); console.log (this._someMethod (1); // or jQuery.someFunction._someMethod (2);});
Thanks!
You can use the This variable, which is present Indicates the object (this is no scope). But if you start new command, this will point to external circuit (in most cases it Window Object = Global Scope).
Example:
function fu () {var a = 10; } Var f = foo (); // nothing in f f = new foo (); // F is nothing in the function bar () {this.a = 10; } Var b = new bar (); //b.a == 10 var b = bar (); // BA == Undefined, but in a global scope
See the syntax of the applied method of BTW, you can see that fist logic is an object, which is it When Your Law Will Be Called.
Then consider this example:
function bar () {console.log (this.a); Console.log (this.innerMethod (10)); } Function foo () {this.a = 10; This.inner.method = Function (A) {Back One + 10; } times. Application (this); } Var f = new foo (); // = & gt; You will find 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 // only a global object (window)
Maybe
var would be better = this;
, before calling for enforcement of the law, but perhaps it is not needed. Not sure
Then, it will definitely work:
function fu () {console.log (this.a); } JQuery.extend ({anyfunc: function (func) {this.a = 10; func.apply (this);}}}; $ .somefunc (foo); // 10 will print.
Comments
Post a Comment