我是初学者,无法理解原型和继承在JavaScript中是如何工作的。我基于这里的代码: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance 我无法弄清楚如何继承属性值,我只能得到“方法”。我想也许更合适的问题是如何在调用子对象时启动父类的字段?
根据上述网站,我写了这样的话:
function Person(name, surname) {
this.name = name;
this.surname = surname;
}
function Student(index) {
this.index = index;
Person.call(this);
}
Student.prototype = new Osoba ();//I tried to insert values here in the constructor, it doesn't work
Student.prototype.constructor = Student;
var x = new Student ('89890');//tried to insert additional values here in the constructor, it also doesn't work
有没有办法创建一个学生并给他一个姓名?
我是一个完全noobie所以请解释,就像你会解释为一个5岁。 PS。我必须在JS中这样做,所以请不要推荐不同的方式,它不会帮助我,谢谢:))
答案 0 :(得分:1)
正确的方法是让您的子构造函数重复所需的参数。
function Student(index, name, surname) {
this.index = index;
Person.call(this, name, surname);
}
var s = new Student ('89890', 'Jan', 'Kowalski');
顺便说一下。此
Student.prototype = new Osoba ();
肯定是一个错字,而不是
Student.prototype = new Person();
你真的不需要这里的参数。原型将在属性值中使用undefined
初始化,这是完全合法的。
答案 1 :(得分:0)
您可以将Student
构造函数更改为此构造函数:
function Student(index, name, surname) {
this.index = index;
Person.call(this, name, surname);
}
call
接受可选参数,因此您可以使用其他参数调用Person
来设置名称和姓氏自己的属性。
答案 2 :(得分:0)
var inherit = function(C, P) {
var F = function(){}; // i created this "proxy" to isolate the Parent constructor
F.prototype = P.prototype;
C.prototype = new F();
};
var Person = function(name, surname) {
this.name = name || '';
this.surname = surname || '';
this.getName = function () {
return this.name;
}
this.getSurname = function () {
return this.surname;
}
};
var Student = function(index, name, surname) {
this.index = index;
Person.call(this, name, surname);
};
inherit(Student, Person);
var student = new Student(0, 'Rodrigo', 'Fonseca');
alert(student.getName());
alert(student.getSurname());