We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi,
I didn't succeed in creating a class in which a button from the DOM can call a local function with local variable. For example, with this script...
function setup() {
myObject = new Test();
}
function Test() {
this.something = 12345;
this.button = createButton('Hello');
this.test = function() {
println(this.something);
}
this.button.mousePressed(this.test);
}
... println says that the argument is undefined
If I put println("123456");
in the test function, it works.
But how can I do to use local variable ?
Thank you.
(I've tried with the "prototype way" without success.)
Answers
I'm not a JavaScript expert, but the first thing I would try is something like this:
JS' keyword variable
this
is tricksy. The object which calls a function becomes itsthis
: @-)https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
In your case above, the object which ends up invoking method test() isn't a Test, i.e. the object created by your
myObject = new Test();
, but the p5.Element object created by createButton()! b-(And when
println(this.something);
is finally executed, it logs outundefined
, b/c the button object doesn't have any property called something. :-BBut don't fret: In order to counter that issue, all JS functions got methods call(), apply() and bind().
The 1st 2 are temporary. However bind() creates a wrapper function over the original 1, which then enforces what its
this
gonna refer to, regardless which object invokes that function: \m/https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
https://alpha.editor.p5js.org/projects/B14hmmI2
https://forum.Processing.org/two/discussions/tagged?Tag=bind()
https://forum.Processing.org/two/discussions/tagged/this
https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
this
automatically! \m/this.test.bind(this)
w/() => this.test()
: :-bdhttps://alpha.editor.p5js.org/projects/Bk_CIU8n
Thank you for your extremely well documented answer ! ^:)^
() => this.test()
works fine.And I've learnt one more way to make a class... :)