3

我对 JavaScript 有点陌生。我知道您应该使用原型来实现对象之间的继承,但是我尝试了以下方法并且效果很好(使用 Visual Studio 2012)。我究竟做错了什么?

function Person(firstname, lastname, age, eyecolor) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.age = age;
    this.eyecolor = eyecolor;

    this.name = function() {
        return this.firstname + " " + this.lastname;
    }
}

function Student(firstname, lastname, age, eyecolor, level) {
    this.level = level;
    Person.call(this, firstname, lastname, age, eyecolor);
}

var per = new Person("Abe", "Lincoln", 45, "green");

var obj = new Student("Abe", "Lincoln", 45, "green", "senior");

当我检查 obj 时,它具有 Person 和 Student 的属性,我可以调用 obj.name() 来获取“Abe Lincoln”。即使在 Visual Studio 即时窗口中,我也可以将所有属性视为彼此的兄弟,正如我所期望的那样。但是我没有使用原型,所以显然这是不对的。

请让我直截了当:)

提前致谢!

4

1 回答 1

1

要使用原型继承,您可以将name方法放在Person.prototype

function Person(firstname, lastname, age, eyecolor) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.age = age;
    this.eyecolor = eyecolor;
}
Person.prototype.name = function() {
    return this.firstname + " " + this.lastname;
}

然后制作一个实例的.prototype对象:StudentPerson

function Student(firstname, lastname, age, eyecolor, level) {
    this.level = level;
    Person.call(this, firstname, lastname, age, eyecolor);
}

// Make the prototype object of the Student constructor inherit from the
//    prototype object of the Person constructor.
Student.prototype = Object.create(Person.prototype)

所以现在你的name方法在所有创建的实例之间共享,而不是为每个实例重新制作。

var per = new Person("Abe", "Lincoln", 45, "green");

var obj = new Student("Abe", "Lincoln", 45, "green", "senior");
于 2013-02-16T21:44:22.347 回答