0

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?

Janis Jansen
  • 996
  • 1
  • 16
  • 36
  • Primarily because `this` inside `area()` will be the `prototype` object, because `this` is always what appears before the last `.`. Secondarily because this is simply not how it's supposed to be used. – deceze Dec 04 '19 at 14:06
  • I wondered why ı need new object ? For that ı use second case . İf area is a property of areaCalc why I can not see x and y values – Mehmet Resul Akyuz Dec 04 '19 at 14:34

1 Answers1

0

The major reason behind this behavior is that new keyword binds the prototype object with the variable. So in your first case when you used area = new areaCalc(5,23) the prototype object was binded with help of new keyword and thus when used this keyword inside prototype object it associates with the object that is invoking it. But in the second case the prototype object was not associated with any object . This is the reason why it gave such behavior.

AyushKatiyar
  • 1,000
  • 8
  • 15
  • Not sure if you're just explaining it in a misleading way, but the prototype object doesn't "bind" with the created object as such… – deceze Dec 04 '19 at 14:23