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.
(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
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>
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.