-1

I am very much new to Javascript please correct my code or suggest the best option

var myApp = {};

myApp.set = function(VAL) {
    myApp.id = VAL;    
}

myApp.get = function() {
    return myApp.id; 
}

function PageLoad() {
    var X = new myApp;
    var Y = new myApp;

    Y.set(20);
    X.set(10);

    alert(X.get());
    alert(Y.get());
} 

It shows last assign value only i.e. 10 :(

Thanks in Advance Manoj

5
  • 4
    Are you sure that's your code as I'm getting the error Uncaught TypeError: myApp is not a constructor. Commented Jul 26, 2017 at 6:56
  • I guess there is a typo, it should be var X= new myApp() (parenthesis) Commented Jul 26, 2017 at 7:04
  • This cannot be your actual code because this code does not run. Please show us your actual code, otherwise this question needs to be closed as invalid. Commented Jul 26, 2017 at 7:04
  • 1
    @Pablo, no, the parentheses are not required, when used with new operator. Commented Jul 26, 2017 at 7:22
  • @NinaScholz Wow, years writing JS code without knowing that... Thank you! Commented Jul 26, 2017 at 7:44

2 Answers 2

1

@Manoj Chavanke Sir Please use this code

 function myApp(){
    }
    myApp.prototype.set = function(VAL) {
        this.id = VAL;    
    }

    myApp.prototype.get = function() {
        return this.id; 
    }

    function PageLoad() {
        var X = new myApp; console.log(X);
        var Y = new myApp; console.log(Y);

        Y.set(20);
        X.set(10);

        alert(X.get());
        alert(Y.get());
    }
    PageLoad();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Karan, Could you please help me to write same code Using Object Literal Notation??
0

I think You override the value myApp.id = VAL;

try this code

 var myApp = [];
myApp.set = function(VAL) {
    myApp.push({id : VAL});
}

instate of

var myApp = {};

myApp.set = function(VAL) {
    myApp.id = VAL;    
}

Because the key is a unique you can't use twice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.