2

How do you pass an argument into an inherited method?

interactiveElement.prototype.moveTowards = function(target){
     console.log(target);
} 

projectile.prototype.fire = function(target){
    interactiveElement.prototype.moveTowards.call(this); //how do I pass target
}

getting error: Uncaught TypeError: Cannot read property '0' of undefined

1
  • Just FYI, the code you posted would not generate such an error. Commented Dec 24, 2013 at 17:45

1 Answer 1

5

If you must use call, simply pass the argument(s) after the "this" parameter:

interactiveElement.prototype.moveTowards.call(this, target); //how do I pass target

but if it's actually an inherited method, you can perhaps simplify it:

this.moveTowards(target);

If moveTowards is anywhere in projectiles prototype chain, you can access it through this instead of using ...prototype...call. Where you do have prototypical inheritance, you typically only use call to reference a function that is "overloaded by a member lower on the chain," e.g. if projectile has a moveTowards and interactiveElement has a moveTowards, and you want to call ineractiveElement's.

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

5 Comments

since you said "must use call", is there a better way?
@wazzaday You were a few seconds ahead of my edit. :-)
You might want to note that when used with call (or its close cousin, apply) a function is not being treated as a method of an object, and the same technique can be used with any function whatsoever. So for instance, you can do Date.prototype.setMonth.call(this, 5) if your object has whatever properties Date.prototype.setMonth requires. It's part of what makes Javascript very different from languages such as Java or C#.
@ScottSauyet The key difference is the (lack of) a strongly-typed compiler. Compiled languages will check the type of the this parameter and make sure it matches the function signature. JavaScript doesn't, and assumes that what you pass will provide everything the function expects. You can have the same mess in C#; but you have to use serialization to do an end run around the strong-type checking. (Then invoking the function will throw an exception when you pass the wrong this in to it, similar to how JavaScript will throw an exception if it can't access the data it tries to.)
@ScottMermelstein: I actually see this as a positive (at least some days I do), although there is certainly some mess underneath it. I do more functional than OO programming in JS, so first-class functions and their features are pretty important to me.

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.