Javascript: Run a function defined outside this closure as if it were defined inside this closure -
i want have function accepts function b argument, , runs b defined within closure scope of a, i.e. has access local variables.
for example, simplistically:
var = function(b){ var localc = "hi"; b(); } var b = function(){ console.log(localc); } a(b); // log 'hi'
the way have found use eval. ec6 give better options maybe?
you can make context explicit , pass b
:
var = function(b){ var context = { localc: "hi" }; b(context); } var b = function(context){ console.log(context.localc); } a(b); // hi
you can use this
new
, prototype
:
var = function() { this.localc = "hi"; } a.prototype.b = function(context){ console.log(this.localc); } var = new a(); a.b(); // hi
or without prototype
:
var = function() { this.localc = "hi"; } var = new a(); a.b = function(context){ console.log(this.localc); }; a.b(); // hi
you can use this
bind
:
var = { localc: "hi" }; function b(foo) { console.log(this.localc, foo); } b.bind(a)("foo"); // hi foo // .call: b.call(a, "foo"); // hi foo
bind
sets context this
. call
takes context it's first argument.
this 1 not good:
var = function(b){ var localc = "hi"; b.bind(this)(); // global object, need `new` create new scope } var b = function(){ console.log(this.localc); } a(b); // undefined
Comments
Post a Comment