My code works when I use my first case. Then I wondered about the second case. When the button is clicked, this.x and this.y values are undefined
My html code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="ObjectKavrami.js">
</script>
<title></title>
</head>
<body>
<button id="demoObjectPrototype" onclick="onObjectWithPrototype()">JavaScript Object</button>
</body>
</html>
Case 1: returns "115":
var areaCalc = function(x,y) {
this.x = x ;
this.y = y ;
}
areaCalc .prototype = {
area: function() { return (this.x * this.y); }
}
var newarea = new areaCalc (5,23);
function onObjectWithPrototype () {
alert(newarea .area());
}
Case 2: returns NaN
var areaCalc = function(x,y) {
this.x = x ;
this.y = y ;
}
areaCalc .prototype = {
area: function() { return (this.x * this.y); }
}
//var newarea = new areaCalc (5,23);
function onObjectWithPrototype () {
areaCalc(2,3);
alert(areaCalc.prototype.area());
//alert(newarea .area());
}
Why can't the method see x and y values?