mike
mike

Reputation: 11

What is the proper way to read a value from another function?

Say I have a this function

function name(){
  var first_name = "mike";
}

I want to pass the value first_name over to another function -- I know you can do it this way:

function name(){
  var first_name = "mike";
  getName(first_name);
}

But say I want to access it without passing over like that

function name(){
  var first_name = "mike";
  getName()
}

In getName how can I access first_name from the name() function?

function getName(){
   console.log(this.first_name)
}

In PHP I know you can do it with $this->first_name, how would this be done in javascript? Also If you can calling another function in javascript, is there a proper way to do it like in PHP $this->first_name()

Thank you in advance

Upvotes: 1

Views: 55

Answers (3)

Kevin Reilly
Kevin Reilly

Reputation: 6252

Kind of naughty, but this is one answer to your question...

var first_name = "mike";

function change_name(new_name) {
  first_name = new_name;
}

function get_name() {
  return first_name;
}

console.log(get_name());

I personally prefer a design pattern like so...

var names = new function() {
  // The 'this' context may change within callbacks and such,
  // so this is one way to save it for later use
  var self = this;

  this.first_name = "mike";
  this.change_name = function(new_name) {
    self.first_name = new_name;
  }
  this.get_name = function() {
    return self.first_name;
  }
}

console.log(names.first_name);
console.log(names.get_name());
names.change_name("kevin");
console.log(names.first_name);

Upvotes: 0

elclanrs
elclanrs

Reputation: 94131

You can't access that variable from any other function unless you pass it explicitly like in naga's solution because first_name is local, only name has access to it. You may want to use prototypes.

function Person(name) {
  this.first_name = name || 'Mike';
}

Person.prototype = {
  getName: function() {
    return this.first_name;
  }
};

var john = new Person('John');
console.log(john.getName()); //=> John

Upvotes: 1

Nagaraj
Nagaraj

Reputation: 145

function name(){
  var first_name = "mike";
  return first_name;
}

function getName(){
  var get_name=name();   
  alert(get_name);
}

Upvotes: 1

Related Questions