简体   繁体   中英

Why do I keep getting an error saying an object property is undefined?

I've been trying to figure out this error in JS and cant understand why its happening. The program is supposed to inherit properties from the person object and add two additional properties, sID and courses. The for loop is then supposed to push values that the user inputs(a minimum of 5) into the properties. The problem I have though is that once it reaches the courses property, which is an array, I keep getting an error saying that courses is undefined. Any help is greatly appreciated.

    // person object
var person = { firstname: "", lastname: "", email: "" }; 
var student = {};
student.prototype = person;
student.prototype.sid = "";
student.prototype.courses = {};



/******************************************************************************
 * your code starts here
 *****************************************************************************/

var answer = null;
function getanswer(string) {
    answer = string;
    return answer;
}
do {
    getanswer(prompt("Please enter your first name, last name, student ID, email and courses (seperated by ',')"));
    var array = answer.split(',');
    answer = array;
    for(var i = 0; i <= answer.length; i++) {
        if (i < 4) {
            student[i] = answer[i];
            alert(student[i]);
        }
        if(i > 3) {
            student.courses[i] = answer[i];
            alert(student.courses[i]);
        }        
    }

} while(answer !== null || answer !== "" );
var student = {};
student.prototype = person;

You seem to be trying modify the prototype of the student instance after it's been created. Generally, this isn't possible in JavaScript. (There may be some non-standard APIs that support this, but you shouldn't be using them.) Also, the prototype of an object is not directly exposed as a public .prototype property on the object. If you want to read the prototype of an instance, you actually need to look it up as through its constructor, as .constructor.prototype (but don't try to modify that!).

To use JavaScript's prototypal inheritance, you need to create a constructor function, and set the prototype on that. For example, in your case:

function Student() {
}
Student.prototype = person;

You can then use this constructor to create a Student instance which will inherit values from person :

var student = new Student;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM