【问题标题】:Constructor function in Javascript isn't workingJavascript中的构造函数不起作用
【发布时间】:2015-05-08 14:48:12
【问题描述】:

我需要提示 5 个属性,然后获取测试分数并获取测试 1、2 和 3 的平均值,然后显示名称和平均值。我无法显示或运行该功能。我的代码有什么问题?

function Student(_firstName, _lastName, _t1, _t2, _t2){

    this.firstName = _firstName ;
    this.lastName = _lastName ;
    this.test1 = _t1 ;
    this.test2 = _t2 ;
    this.test3 = _t3 ;

    this.fullName = function() { return this.firstName + " " + this.lastName } ;

    this.calcAverage = function() { return (this.test1 + this.test2 + this.test3) / 3 } ;

}

var name1 = prompt("Enter the first name:") ;
var name2 = prompt("Enter the last name:") ;
var te1 = parseInt(prompt("Enter the first test score:")) ;
var te2 = parseInt(prompt("Enter the second test score:")) ;
var te3 = parseInt(prompt("Enter the third test score:")) ;

var person = new Student(name1, name2, te1, te2, te3) ;

document.write(+name1+ " " +name2+ " " + person.calcAverage() +) ;

【问题讨论】:

  • 这是做什么的?您是否在控制台中遇到任何错误?
  • 你有很多错误。参数名称是双精度的,document.write 有不必要的“+”号。

标签: javascript function prompt function-constructor


【解决方案1】:

修正你的错别字:

function Student(_firstName, _lastName, _t1, _t2, _t3) {
                                                   ^^ _t3, not _t2

document.write(+ name1 + " " + name2 + " " + person.calcAverage() +);
               ^^ remove +                                        ^^ remove +

DEMO

【讨论】:

    【解决方案2】:

    工作代码...

    function Student(_firstName, _lastName, _t1, _t2, _t3) {
    
        this.firstName = _firstName;
        this.lastName = _lastName;
        this.test1 = _t1;
        this.test2 = _t2;
        this.test3 = _t3;
    
        this.fullName = function () {
            return this.firstName + " " + this.lastName
        };
    
        this.calcAverage = function () {
            return (this.test1 + this.test2 + this.test3) / 3;
        };
    
    }
    
    var name1 = prompt("Enter the first name:");
    var name2 = prompt("Enter the last name:");
    var te1 = parseInt(prompt("Enter the first test score:"));
    var te2 = parseInt(prompt("Enter the second test score:"));
    var te3 = parseInt(prompt("Enter the third test score:"));
    
    var person = new Student(name1, name2, te1, te2, te3);
    
    document.write(+name1 + " " + name2 + " " + person.calcAverage());
    

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 2018-07-17
      相关资源
      最近更新 更多