Hello, I’m having a problem where I can’t acess the variables “this.x” and “this.width” from where I want. I know why just dont know how to solve it… Please help me.
What you’ve done seems right so far. Now all you have to do is to create specialObject from the SpecialObject constructor, and it’s from specialObject that the this keyword will apply.
You’re not replying to Paul’s response but are reposting your question? What on earth makes you do that? Also, I’m wondering why you are so proficient in writing Javascripts but do not know the principles of the use of this? If this is a homework assignment at which you just copied and pasted the script that you were supposed to analyze, be honest about it and tell us.
Paul’s didn’t make a question… though I’m just saying that I’ve done what he sad but I forgot to say it on the first post.
To awnser your question… I’m being totally honest, if I’m proficient its because I’m used to program Java. If I don’t know the principles of the use of “this” is because this is my first attempt on making a project in javascript and I don’t have javascript lessons… so I’m a totally newbie trying to learn…
I won’t go in to why Java is not JavaScript here, but it can be an interesting discussion to have at some other time.
The reason why the this keyword is not retrieving the x property, is because the canvas doesn’t have that property on it.
Why the canvas? Because that is the context under which the function is being run.
If you want to refer to the specialObject object, it can help to cache a reference to it so that you can then refer to it later on.
this.needBoundaries = function () {
var objRef = this; // local reference to specialObject
canvas.addEventListener('mousemove', function (e) {
...
// use objRef.x in here to gain access to its x property
Thank you for your answer, I had that idea about the problem being the context that it was in but I would never remember of making a var with the this so thank you very much for that, though there is another problem which I’m not being able to understand.
And, on another place I added a call to the setWidth once the mouse was down.
What happens now it that the width is undefined until I click on the mouse… Output:
0 - -1
0 - undefined
0 - 100
First line is written by the last console.log(objRef.x + " - " + objRef.width);
Second Line is written by the first console.log before the mouse clicking and finally, third line is written by the same first console.log after the mouse is down…