If we want to call a function that modifies an object's properties, is there another way to self-reference other than using obj.property inside the function?
Example (in other languages such as Java):
public void doSomething(int arg)
foobar = arg;
end
However example with Matlab:
classdef Foo < handle
properties
foobar = 0;
end
methods
function obj = Foo(arg)
if nargin > 0
obj.foobar = arg;
end
end
function doSomething(obj, arg)
obj.foobar = obj.foobar + arg; % Needed to reference the current object
end
end
end
With more properties, it could start to look messy from writing all the "obj."
I've seen some people use "o." (less characters looks a bit nicer), but I was wondering if there was a better way (ie: without using obj.) or is this the only option?
Thanks!
This is the only option, yes. Passing obj
as the first argument is necessary because matlab chooses the right version of a function using "dynamic dispatch". I.e. if you have two classes and both define doSomething
functions, matlab will call the right version based on the type of the first argument; this is why the first argument of a member function (with the exception of the constructor) always needs to be the object itself.
Whereas in java, something entirely different is going on, since it's a compiled language, not an interpreted one. There it's a case of polymorphism, etc etc.
So no. There is no shortcut. This is just how matlab classes work.