I'm building a library with a some methods and I have a method extend
and a method load
. I'd LIKE it to work like this:
Core.extend('name',function(message){
this.innerHTML = message;
});
Then to actually run this you'd do:
Core.load('name','Hey!');
Core.extend()
creates a <div>
element with a unique id based on the name. I want to make this
== the generated <div>
.
I know about .call()
and .apply()
, obviously, but it doesn't change this
it only changes the callback params in extend. Here's the code for extend and load:
Core.extend()
var extend = function(name,func){
name = name || '';
func = func || function(){};
if(typeof extensions[name] == 'undefined'){
extensions[name] = func;
}
else{
if(errors){
throw new Error('Core extend() error: the extension "'+name+'" already exists');
}
}
}
Core.load()
Note this is the main line: extensions[name].call(this,widgetElement,params);
var load = function(name,params,sel){
name = name || '';
params = params || '';
sel = sel || '';
if(typeof extensions[name] !== 'undefined'){
var widgetElement = document.createElement(settings.widgetWrapperElement);
widgetElement.setAttribute('id',settings.prefixOnWidgetId+name);
sel.appendChild(widgetElement);
extensions[name].call(this,widgetElement,params);
}
else{
if(errors){
throw new Error('Core load() error: the extension "'+name+'" doesn\'t exist');
}
}
}
this is not a variable. It is a keyword. You cannot change the value of this .
It's totally possible to redefine a function object into whatever you want upon the first call. The reason this is possible is because the assignment evaluations is handled from right to left. This means that the scope of the function is captured when you execute it (in this case, when you call the function).
By-Value: The value of a variable is sent to function. The actual parameter cannot be changed by function.
The Function.call
function's first argument should be what you want to set as the this
object.
That means, you should change
extensions[name].call(this, widgetElement, params);
to
extensions[name].call(widgetElement, params);
in order to pass widgetElement
as the this
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With