简体   繁体   中英

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

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

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

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM