Javascript代码,没有弄清楚是什么错

时间:2015-02-23 10:24:06

标签: javascript html

我刚刚恢复功能而没有计算,出了什么问题? 我无法弄清楚这一点......这太烦人了

<script type="text/javascript">
    function Human(age, name, lastname) {
        this.age = age;
        this.name = name;
        this.lastname = lastname;
        this.born = born;
    }
    function born() {
        var currentyear = 2015;
        var born = this.age - currentyear;
    return born;
    }

    var asaf = new Human(16,"Asaf","shlush");
    var daniel = new Human(19 , "Daniel" , "Bivas");

    document.write(asaf.born);

5 个答案:

答案 0 :(得分:1)

您需要调用方法document.write(asaf.born());

答案 1 :(得分:0)

天生的功能应该在人类声明中。

function Human(age, name, lastname) {
    this.age = age;
    this.name = name;
    this.lastname = lastname;

    this.born = function () {
        var currentyear = 2015;
        var born = this.age - currentyear;
        return born;
    }
}


var asaf = new Human(16,"Asaf","shlush");
var daniel = new Human(19 , "Daniel" , "Bivas");

document.write(asaf.born());

请注意最后一行中函数调用的括号。

答案 2 :(得分:0)

问题是born对象上没有定义函数Human

试试这个:

 function Human(age, name, lastname) {
    this.age = age;
    this.name = name;
    this.lastname = lastname;
    this.born = function(){
        return 2015 - this.age;
    };
};

var asaf = new Human(16,"Asaf","shlush");
asaf.born() // 1999

答案 3 :(得分:0)

您实际上需要调用该函数:asaf.born()

您也可以考虑将born添加为Human原型的方法。你得到了相同的结果,但它可能是更好的练习。类似的东西:

function Human(age, name, lastname) {
    this.age = age;
    this.name = name;
    this.lastname = lastname;
}

Human.prototype.wasBorn = function () {
    var currentyear = 2015;
    var born = this.age - currentyear;
    return born;
}

Here you can see both results working.

答案 4 :(得分:0)

您只需在javascript代码中编写调试器,然后在浏览器中使用inspect element console屏幕打开它,然后刷新它,然后在浏览器中调试您的javascript代码,就可以自行检查。

您可以简单地检查哪些功能可以调用,哪些功能不可以。您还可以检查那里所有元素的值。 所以,你可以检查if函数是否返回born的值?