0

I had a doubt.Is this possible to call one function/method present inside one class using object prototype in Javascript ? If possible then can anybody make the below code correct.

(function(){
    window.Peer=function(){
        var peer=this;
        peer.getMessage=function(){
            alert("hello!!! This is very good site.")
        }
    }
})();


<button type="button" id="btn">Click here</button>
<script>
document.getElementById('btn').onclick=function(){
    Peer.prototype.getMessage();
}

The above code throwing error.Please give me some idea to resolve this.

4
  • you can test with Inspect Element within Console Commented Jul 11, 2015 at 10:33
  • you can run it as it using Peer(getMessage()) or Peer.call(getMessage()) Commented Jul 11, 2015 at 10:36
  • 2
    FYI you are getting an error because you haven't added the function to Peer.prototype Commented Jul 11, 2015 at 10:38
  • @Jaromanda X : Can you make this correct.? Commented Jul 11, 2015 at 11:31

2 Answers 2

1
(function(){
    window.Peer=function(){}
    window.Peer.prototype.getMessage=function(){
        alert("hello!!! This is very good site.")
    }
})();
<button type="button" id="btn">Click here</button>
document.getElementById('btn').onclick=function(){
    var peer = new Peer();
    peer.getMessage();
}

you can treat Peer as an object

Sign up to request clarification or add additional context in comments.

1 Comment

I know this but i want to use prototype.
0

Every first thing I would suggest you to read more about JavaScript Object

getMessage is a function attached with peer variable which has local scope. You can't access it from outside world unless you create a object of Peer.

<html>
<head>
<script>

(function(){
    window.Peer=function(){
        var peer=this;
        peer.getMessage=function(){
            alert("hello!!! This is very good site.")
        };
    }
})();

window.onload=function(){
    document.getElementById('btn').onclick=function(){
        var peer = new Peer();
        peer.getMessage();
    };
}
    </script>
    </head>

<body>
    <button type="button" id="btn">Click here</button>    
</body>
</html>

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.