1

I am new to javascript and many aspects seem counter intuitive. Am I correct in understanding that if I define:

var A = function() {
    return {
        d:"property-of-object-returned-by-constructor",
        method:function() {
            d = "Not my property";
        }
    }
}

myObj = new A();

Am I correct that the only way to refer to property d inside of myObj.method() is to use this.d?

For example, am I correct that as it stands myObj.method() doesn't change the property d but actually creates a global variable d that is completely unrelated to myObj.d?

I believe that is what I am seeing in my code, but it is counter intuitive that "this" would be the sole way to refer to one's own properties, rather than simply referring to them directly. So maybe I am misunderstanding something.

1 Answers1

2

Yes, d would be defined as a global variable if you omitted 'this'

if you wanted a variable only accesible from inside your objects methos you would have to append 'var' to it:

var d = "string";

if you wanted to reference it after you'd used it as a class to create a new object, then you would either have to return it as a string:

var d = "string;
return d

or as anothe nested obeject like you are instanciating the class in the firstplace:

var d="string";
return {'val':d}
eskimomatt
  • 195
  • 9
  • So there is not a way to reference an objects own properties within an objects own methods except by using "this"? If I have properties x,y to add and put into property z I need to write out this.z = this.x + this.y? –  May 19 '15 at 16:21
  • if it is within that function, you could use a local var - var x=10;var y=20; etc.. but to keep conflicts down, i'd use 'this' – eskimomatt May 19 '15 at 16:25