gpt4 book ai didi

不使用原型(prototype)的Javascript父子继承

转载 作者:行者123 更新时间:2023-11-29 15:43:48 26 4
gpt4 key购买 nike

我对 JavaScript 有点陌生。我知道您应该使用原型(prototype)来实现对象之间的继承,但我尝试了以下方法并且效果很好(使用 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 即时窗口中,我也可以将所有属性视为彼此的同级属性,正如我所期望的那样。但我没有使用原型(prototype),所以显然这是不对的。

请让我直说:)

提前致谢!

最佳答案

要使用原型(prototype)继承,您需要将 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;
}

然后让Student.prototype对象成为Person的实例:

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

关于不使用原型(prototype)的Javascript父子继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14915408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com