0

This is what I think is best for making an object in js

    function obj(){
        var x = "hi";
        this.getX(){return x;}
    }
    var y = new obj()
    console.log(y.x); //this returns undefined

But from what I have seen, using this.variable is used more often in object creation.

I am thinking in java where things should be "private" in a class (note I have read about closures), does that apply in js?

What is considered the best way of object creation?

capa_matrix
  • 115
  • 3
  • 10
  • 2
    http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – Keatinge May 13 '16 at 00:27
  • Please show some code to demonstrate what your are asking exactly. From the text of the question, it sounds like a "local variable" is the closer equivalent in Java. – Thilo May 13 '16 at 00:29
  • I was taking that from various posts I read about var vs this. Also I am reading that other link to ee if it helps. Thanks – capa_matrix May 13 '16 at 00:34
  • @Racialz I now get the concept of closure but, in javascript would I want to program in that manner or would it be better to use "this.variable" – capa_matrix May 13 '16 at 00:39

1 Answers1

4

It sounds like you're trying to apply Java concepts to JavaScript, but things works completely differently in JS. You should check out the MDN article on JavaScript closures.

var variables exist in the closure. They are accessible from any function declared in the same scope.

var me = 'hello';
function someFunction() {
    console.log(me); 
}
someFunction(); //prints 'hello' to console

this variables will be directly accessible, even outside the scope, in the resulting object.

function someFunction() {
    this.me = 'hello';
}
var instance = new someFunction();
console.log(instance.me); //prints 'hello' to console
tonymke
  • 752
  • 1
  • 5
  • 16
  • thanks, that looks more detailed and will look through it. But am I wrong in using it the way I do above? Or no? I'm so confused. It does what I want. thanks – capa_matrix May 13 '16 at 01:00
  • Without telling us what you want to achieve exactly, there is no "wrong" (or rather, everything that works is "right"). Both patterns have their uses. – Thilo May 13 '16 at 07:29