0

New to JavaScript. I'm trying to call a method of an object passed as an argument to another method. I keep getting the error that the argument is null or the argument doesn't have a method named x.

In a strongly typed language like c# you can do this

public class Context 
{
  public void moveTo(int x, int y) {...}
  public void lineTo(int x, int y) {...}
}
public class Square
{
  public void draw(Context c, int x, int y) {
    c.moveTo(x,y);
    c.lineTo(x+10,y+5); //etc
  }
}
public class Design
{
  ctx = new Context();
  s = new Square();
  s.draw(ctx,5,10);
}

Instead of a Square, I'm drawing something more complex. But in my attempt at Javascript, when it compiles it gets an error in draw that c is null, has no method lineTo.

What is the Javascript way of doing this?

1
  • 4
    Show what you tried in Javascript that wasn't working. Commented Jun 24, 2017 at 3:24

2 Answers 2

1

Well, in JavaScript you can just do that:

let sum = {
  operation: (a, b) => a + b
};

let minus = {
 operation: (a, b) => a - b
};

let obj = {
 applyOperation: (obj, a, b) => obj.operation(a, b)
};

obj.applyOperation(sum, 1, 2);    // => 3
obj.applyOperation(minus, 1, 2);  // => -1

if you pass an empty object ({}) you'll receive a TypeError exception, in that case would be something like: TypeError: obj.operation is not a function

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

Comments

0

Elton is correct. My issues were the assignment in an if statement syntax that javascript allows like C does (I had gotten used to C# prevention of this) and unfamiliarity with Chrome debugging as it was a runtime error not a compile error.

That actual error message was:

Uncaught TypeError: Cannot read property 'moveTo' of null

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.