-1

I'm getting really confused when it comes to javascript object variables. If I'm creating an object constructor, what the difference between using this. and using var? EG:

var myObj = function(x){ 
    this.thing = x;
    var otherThing = 20;
    var lastThing = "I wish I knew more about javascript objects";
}

The other thing is when setting a this. variable you call it within the object using, in the case above:

   this['thing'];

Is that right?

Thanks in advance.

Strontium_99
  • 1,771
  • 6
  • 31
  • 52

2 Answers2

1

Here is a reference to object oriented javascript on MDN:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

If you use the var keyword then those variables will be private to your object. You won't be able to do myObj.otherThing

If you use this, then the variable is a property of your object, so you can use myObj.thing

When you call a variable from within the object you would use this.thing, outside the object you would use myObj.thing

Hope that helps.

Michael Dowd
  • 221
  • 1
  • 5
0

That's right. Be careful :

var fn = function( x ){
    this[ 'thing' ] = x;
    return this;
}

console.log( fn( 2 ) ); // return window, and function set window[ 'thing' ] = 2
console.log( fn.apply( document, [ 3 ] ) ); // return document, and function set window.document[ 'thing' ] = 3

"this" refer to context where is executed function. If you run function in window like fn(2) the context is the window. Use apply to change the context. Then if you would like thing to be in the current function, then use var thing in function context;

window[ 'thing' ] // is the same as window.thing
window[ '2' ] // is the same as window[ 2 ], but not window.2 (syntax error)
karkael
  • 431
  • 2
  • 9