-1

what's wrong here? and what is the different if I declared like this

mat.prototype = function discountedMat(){

}

http://jsfiddle.net/Tu8tS/

function mat(brick,sand,water) {
    this.mat = brick;
    this.sand = sand;
    this.water = water;

    var cal = function(){
        return this.mat * this.sand * this.water;
    };
}

var material = new mat(44,2,9);
console.log(material.cal());
user3106579
  • 643
  • 1
  • 6
  • 15
  • 1
    What exactly is your question? – thefourtheye Dec 24 '13 at 06:49
  • I think this answer can help you out: http://stackoverflow.com/a/16063711/1641941 – HMR Dec 24 '13 at 07:10
  • its all about scope chk this answer to understand http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript –  Dec 24 '13 at 07:11

3 Answers3

1

If you are asking why material.cal() fails,

it is because,

var cal = function(){

cal is just a local variable in the mat function, it will not be exposed in the objects, created with mat function constructor. To fix that, add the function definition to the current object, like this

this.cal = function(){

It is normally good and efficient to define the methods as part of the protoype, like this

mat.prototype.cal = function() {
    ...
}

because, you don't have to create a function object every time the function constructor is called.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

You just declared a local variable cal inside the mat function.

The normal practice is declaring it on the prototype of the function.

function mat(brick,sand,water) {
    this.mat = brick;
    this.sand = sand;
    this.water = water;   
}

mat.prototype.cal = function(){
    return this.mat * this.sand * this.water;
};
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • I've seen some code use function within a function, just like I did cal in mat function, what do you think it does? – user3106579 Dec 24 '13 at 06:55
0

Try this code: Fiddle

JS:

function mat(brick,sand,water) {
    this.mat = brick;
    this.sand = sand;
    this.water = water;

    this.cal = function(){
        return this.mat * this.sand * this.water;
    };

}

var material = new mat(44,2,9);
 console.log(material.cal());
Manoj
  • 1,860
  • 1
  • 13
  • 25