0

Javascript,

How do I get the variable from within a variable to be used through-out the script?

<script>
var variable = function(snap) {
   var header= snap.head();
   var name = snap.name();
};

alert(variable.name);
</script>

I want to be able to use variable.name outside the function. If possible.

Brian
  • 141
  • 1
  • 3
  • 13
  • You can't, at least not that way. Read up on "closures" and you'll understand why this is not possible. – elclanrs May 20 '13 at 01:37
  • Create a container object and [look here](http://stackoverflow.com/questions/3750082/javascript-oop-best-practices/13074081#13074081) for direction on how to change the accessibility for what you want.. Works very well for pages and controls. – Brett Weber May 20 '13 at 01:56

2 Answers2

3

Treat the "variable" function as a class. Change the inner variables to PROPERTIES OF the function. (And don't name a function "variable", it's just icky).

var Variable = function(snap) {
    this.name = snap.name() // 
}

var the_var = new Variable(snap_func);
console.log (the_var.name());
rGil
  • 3,719
  • 1
  • 22
  • 30
  • +1 this constructor pattern seems to be what the OP is trying to accomplish – Christophe May 20 '13 at 01:48
  • Says snap_func not defined. – Brian May 20 '13 at 01:59
  • snap_func is just what I made up - you will pass the name of whatever function you are trying to pass into the `Variable` method. – rGil May 20 '13 at 02:03
  • There are lots of good tutorials on constructor methods in javascript, [this being one](http://www.phpied.com/3-ways-to-define-a-javascript-class/). You should also read up on scope in JS - [This was the first google search entry I found](http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/). This can help you start to get the basics... – rGil May 20 '13 at 02:08
  • So how can I call the 'this.name = snap.name();' out of the function? – Brian May 20 '13 at 02:09
  • Edited so you can see how to 'call' the function outside the Variable function. – rGil May 20 '13 at 02:13
0

You can remove var and make it work that way. If you can't do that then make a new method like getName and define it like this.

this.getName = function(){
    return name;
}

To call it, you have to use variable.getName();

Its better to make an accessor method like this so you can check if name has something you might not want to send out.

  • Encouraging the OP to set a global variable on the window object is bad practice as it can be overwritten from anywhere, and the code is not modulized to the area it concerns breaking the basic principles of design for effective and controlled javascript coding.. – Brett Weber May 20 '13 at 02:00