Changing and value of variable in function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Lagon666
    New Member
    • Jun 2009
    • 22

    Changing and value of variable in function

    How can i change the value of a variant that defined in a function for ever?

    Code:
    function test()
    {
    this.data = 'hello';
    }
    
    function change()
    {
    var a = new test();
    a.data = 'hi';
    alert(a.data);
    }
    
    change(); // return hi
    
    var b = new test();
    alert(b.data); // return hello
    Is any solution for return the new value of 'data' variable that replaced using change() function.
  • hsriat
    Recognized Expert Top Contributor
    • Jan 2008
    • 1653

    #2
    Code:
    function test() //<<== is a class
    {
    this.data = 'hello';
    }
    
    function change()
    {
    var a = new test(); //<<== is object of test class
    a.data = 'hi'; // you change data variable of 'a' object but not 'test' class.
    alert(a.data);
    }
    
    change(); // return hi //of course!
    
    var b = new test(); //another object... not the last object a
    alert(b.data); // return hello //of course... you didn't change this 'b' object
    Solution:
    Make the function within that test function

    Code:
    function test() {
        this.data = "hello";
        this.change = function() {
            this.data = "hi";
        }
    }
    
    var a = new test();
    alert(a.data); //will return hello
    a.change();
    alert(a.data); //will return hi

    Comment

    • Lagon666
      New Member
      • Jun 2009
      • 22

      #3
      Thanks

      But is it possible to return changed value (hi) using another object defining ('b' object), but not using 'a' object?
      Something like last line.

      Code:
      function test()
      {
      this.data = 'hello';
      this.change = function()
      {
      this.data = 'hi';
      }
      }
      
      var a = new test();
      alert(a.data); // will return hello
      a.change();
      alert(a.data); // will return hi
      
      var b = new test(); // or 'var b = test();' but its wrong
      alert(b.data); // return hello (hi?)

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5390

        #4
        basicly you would need to call the change method to get 'hi' returned or create a derived obj like this:

        Code:
        function test() {
            this.data = 'hello';
            this.change = function() {
                this.data = 'hi';
            }
        }
        
        var a = new test();
        alert(a.data); // will return hello
        a.change();
        alert(a.data); // will return hi
        
        function myTest() {
            this.change();
        }
        
        myTest.prototype = new test();
         
        var b = new myTest();
        alert(b.data);
        kind regards

        Comment

        Working...