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.

5
  • 1
    stackoverflow.com/questions/3127429/… Commented May 19, 2015 at 16:13
  • you could just return and object map from you internal function? Commented May 19, 2015 at 16:14
  • 1
    @eskimomatt that sounds like an idea, but like he said, beginner, so I guess that doesn't help him understand the intricacies of scope. Commented May 19, 2015 at 16:14
  • @Daniel Yes, that is an excellent reference on "this", but I am not asking whether "this" refers to the property, but what happens when I omit "this". Commented May 19, 2015 at 16:15
  • yep, so sorry! so in theory, if 'this' is ommited then, yes, 'd' is a global var Commented May 19, 2015 at 16:19

1 Answer 1

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}
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.