Andrew
Andrew

Reputation: 1

Pass vars to other method javascript

I want to pass var "firstWord" with saved value in it from one method to another.

var obj = {

    getWords: function () {

        var words = [];

        $('input').each(function () {
            words.push($(this).val());
        });

        var firstWord  = words[0],
            secondWord = words[1],
            thirdWord  = words[2];

    },

    pushWords: function () {

        Array.prototype.insert = function (index, item) {
            this.splice(index, 0, item);
        };

        var fruits = ["Banana", "Orange", "Apple", "Mango"],
            randomPosition = (Math.floor(Math.random() * (5 - 2 + 1)) + 1);

        fruits.insert(randomPosition, firstWord);


        $('body').append(fruits);
    }

};

Probably my code is wrong a bit, but is there any possibility to do that in this case?

Upvotes: 0

Views: 41

Answers (4)

epascarello
epascarello

Reputation: 207501

So make it a property of the object.

var obj = {

  _words : [],
  
  setWords : function () {
     this._words = ["hello","world"];
  },
    
  pushWords : function () {
    this._words.push("foo");  
  },
    
  readWords : function () {
      console.log(this._words); 
  }
  
}

obj.readWords();
obj.setWords();
obj.readWords();
obj.pushWords();
obj.readWords();

Upvotes: 0

Nouphal.M
Nouphal.M

Reputation: 6344

Try to return the array like below,

 getWords: function () {

        var words = [];

        $('input').each(function () {
            words.push($(this).val());
        });

       return words;

    },

and in push words

    pushWords: function () {

            var arr = this.getWords();
            ................
            ................
            ................
           fruits.insert(randomPosition, arr[0]);
    }
   $('body').append(fruits);

since var firstword,secondword and thirdword are only accessible inside the getwords function you must try to return it. And don't forget to validate the return value before you use it. Hope it helps..

See example here https://jsfiddle.net/xz0ofkjx/

Upvotes: 0

Syed Ali Hamza
Syed Ali Hamza

Reputation: 213

One way it to pass one function's value to the other, like:

function one(){
var var1 = "hello";
two(var1);
}

function two(x){
alert(x);
}

This should print "hello" for you. The other way is to declare your firstWord as a global variable.

Upvotes: 0

BassT
BassT

Reputation: 849

If you declare a varible with the var keyword, it's a only available in the function. Leave it out and you'll have a global variable, which you can access from other functions as well. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)

Upvotes: 0

Related Questions