Kin
Kin

Reputation: 4596

How to use the function only when it is called?

Sorry - i can not exactly explain the problem, so i show you an example.

window.onload = function() {
    var obj = new classs(2);
    alert(obj.x2);

    function classs(value){
        this.value = value;

        var multiplication = function(value, n){
            console.log(n);
            return parseInt(value) * parseInt(n);
        }

        this.x1 = multiplication(this.value, 1);
        this.x2 = multiplication(this.value, 2);
        this.x3 = multiplication(this.value, 3);
    }
}

So i call only obj.x2, but console.log(n); prints 3 times. What i am doing wrong?

Upvotes: 0

Views: 68

Answers (3)

Kirby
Kirby

Reputation: 3709

When classs is executed, the multiplication function is executed three times when x1, x2, and x3 are set. That's why console.log is hit 3 times. The alert, on the other hand, only happens once since you call alert on obj.x2.

Upvotes: 0

Guffa
Guffa

Reputation: 700362

Reading the x2 property doesn't cause anything to be logged to the console, it will only read the already calculated value.

The properties x1, x2 and x3 are calculated when the classs object is created, so the values are logged to the console before you read the x2 property. If you comment out the line that uses the x2 property, the values will still be logged.


If you want to do the calculation after the object is created, you need to use functions instead:

this.x2 = function() { multiplication(this.value, 2); }

Usage:

alert(obj.x2());

Upvotes: 3

Dmytro Pastovenskyi
Dmytro Pastovenskyi

Reputation: 5419

because you simply make call of multiplication 3 times

when you create your object

var obj = new classs(2);

it execute code inside of it and as you can see there are 3 call of function "multiplication".

this.x1 = multiplication(this.value, 1);
this.x2 = multiplication(this.value, 2);
this.x3 = multiplication(this.value, 3);

Upvotes: 0

Related Questions