In a recent coding scenario, I encountered this situation: I attempted to define the func1()
function and add several static methods to it simultaneously by passing it through the _init()
function along with a hash containing properties to attach. However, I later discovered that the function did not remain declared within the current scope after the _init()
function executed its task. It was only temporarily defined and then garbage-collected after the _init()
run (to the best of my knowledge). Here is an excerpt of the code:
//
// #_init
// merge src{} into target{}, overwriting
//
var _init = (function (target, src) {
var _ = this;
if (_.isobj(target))
_.keys(src).forEach(_.pass, {
src : src,
target : target
});
return target;
}).bind({
isobj : (function (node) {
return node === this(node);
}).bind(Object),
keys : (function (node) {
return this.keys(this(node));
}).bind(Object),
pass : function (field) {
this.target[field] = this.src[field];
}
});
I was hoping to 'batch-init' it here by adding static methods at the same time:
_init(function func1(e) {
var _api = func1.pop(arguments);
var node = this;
// and stuff...
}, {
pop: Function.prototype.call.bind(Array.prototype.pop),
// ...etc
});
Subsequently, when I attempted to reference it later on, I encountered an error:
x = func1();
// ReferenceError: func1 is not defined
// x = func1()
Assigning the output of _init()
to var func2
resolved the issue as I could now reference and utilize the function. What confuses me is that when using console.log()
to display func2
, it shows 'func1()'. Yet, trying to directly reference func1
results in a ReferenceError:
//
// #func2
//
var func2 = _init(function func1() {
return func1.pop(arguments);
}, {
pop: Function.prototype.call.bind(Array.prototype.pop)
});
console.log(typeof func2, func2, func2(1,2,3));
// function func1() 3
console.log(func1(1,2,3));
// ReferenceError: func1 is not defined
// console.log(func1(1,2,3));
//
Can anyone clarify why the reference to func1
was not successfully created, yet it seemed available to func2
(which was able to use it)?