开发者

Change a functions "this" value in JavaScript

开发者 https://www.devze.com 2023-03-27 16:26 出处:网络
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:

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(开发者_JAVA百科)

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


In order to get this set appropriately, you execute the callback function with either .call() or .apply() and pass in the this that you want.

So, inside of Core.extend() or Core.load(), when you are about to call the passed in function, you would use fn.call(xxx, message) where fn is the function passed to the Core.extend() as a parameter, xxx was the div element you had just created.

I don't follow exactly what all you're trying to do, but you set the this point with either .call() or .apply(). You can see how they work here and here. In your code, it looks like you should change this:

extensions[name].call(this,widgetElement,params);

to this:

extensions[name].call(widgetElement, params);

since the first argument to .call is what you want the this pointer to be and the second argument is what you want to be passed to the function and your function in your example only takes one parameter so I presume that's all you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消