William Biesty
William Biesty

Reputation: 11

JavaScript call method of object passed as argument

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?

Upvotes: 0

Views: 58

Answers (2)

William Biesty
William Biesty

Reputation: 11

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

Upvotes: 0

Elton Viana
Elton Viana

Reputation: 301

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

Upvotes: 1

Related Questions