Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change a functions "this" value in JavaScript

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');
    }
  }
}
like image 282
Oscar Godson Avatar asked Aug 13 '11 05:08

Oscar Godson


People also ask

Can we change the value of this in JavaScript?

this is not a variable. It is a keyword. You cannot change the value of this .

Can you redefine a function in JavaScript?

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).

Can you change the value of a function parameter?

By-Value: The value of a variable is sent to function. The actual parameter cannot be changed by function.


1 Answers

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.

like image 136
Peter Olson Avatar answered Oct 06 '22 18:10

Peter Olson