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');
}
}
}
The
Function.callfunction’s first argument should be what you want to set as thethisobject.That means, you should change
to
in order to pass
widgetElementas thethisobject.