# More Kinds of Methods

#1

Why wouldn't this work? It returns NaN.

``````var square = new Object();

var calcPerimeter = function(x) {
return this.x * 4;
};
var calcArea = function (y) {
return this.y * this.y;
};
// help us define an area method here

square.calcPerimeter = calcPerimeter;
square.calcArea = calcArea;
var p = square.calcPerimeter(4);
var a = square.calcArea(2);
console.log(p);
console.log(a);``````

#2

Take a look at this method:

``````var calcPerimeter = function(x) {
return this.x * 4;
};``````

You use `this.x`, this means that your object must have the `x` property. And your function also takes a parameter, but you don't use it in the body of the function. You have mixed two completely different techniques.

And if we have a square... do we really need lengths of two sides?

Correct code with use of properties:

``````var square = new Object();

// functions without parameters!
var calcPerimeter = function() {
return this.x * 4;
};
var calcArea = function() {
return this.x * this.x;
};

// define fields and methods
square.calcPerimeter = calcPerimeter;
square.calcArea = calcArea;
square.x = 4;

var p = square.calcPerimeter();
var a = square.calcArea();
console.log(p);
console.log(a);``````

Correct code with use of parameters:

``````var square = new Object();

// functions refer to parameters, not to properties
var calcPerimeter = function(x) {
return x * 4;
};
var calcArea = function(x) {
return x * x;
};

square.calcPerimeter = calcPerimeter;
square.calcArea = calcArea;

// we have to pass values to methods
var p = square.calcPerimeter(4);
var a = square.calcArea(4);
console.log(p);
console.log(a);``````

The first solution is better and it's consistent with the OOP.

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.