0

抱歉 - 我不能准确地解释这个问题,所以我给你举个例子。

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);
    }
}

所以我只打电话obj.x2,但console.log(n);打印了 3 次。我做错了什么?

4

3 回答 3

3

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());
于 2012-10-10T18:17:00.530 回答
0

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);
于 2012-10-10T18:16:23.777 回答
0

执行 classes 时,设置 x1、x2 和 x3 时,乘法函数执行 3 次。这就是为什么 console.log 被命中 3 次的原因。另一方面,警报只发生一次,因为您在 obj.x2 上调用警报。

于 2012-10-10T18:19:04.700 回答