1

ive been using call a bit recently in some tutorials I've been following but am more used to passing the object. I was wondering is it best to use call. What's the most efficient way?

var editor = function(someParam){
 //do something with this
}

var testFunction function(someParam){
  editor.call(this, someParam);
} 

or

var editor = function(obj, someParam){
  var self = obj;
}

var testFunction function(someParam){
  editor(this, someParam);
}

2 Answers 2

2

I would stick with passing the object to the function as long as you can structure the function that way. I see call more like a utility if the function cannot be changed anymore and you really have to inject a different this context. Also, consider using the prototype approach if your function is bound very close to some object that you want to call the function on.

Also, call will be less performant than passing the object to the function, as the injection of a different this has some overhead.

Sign up to request clarification or add additional context in comments.

Comments

0

In some cases call is very useful, for example when adding event handler:

window.addEventListener('load', function(){
    var cb = document.getElementById('myCheckBox');
    cb.addEventListener('change', onchange);
    onchange.call(cb); // sets `cb` as `this` in `onchange` function
});

function onchange(){
    // I'm using 'this' for current element
    if(this.checked)
       alert('checked');
}

In this case onchange will be called on window load and every time checkbox checked state changes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.