Javascript JS中的继承,继承属性和值
我是一个初学者,无法理解JavaScript中的原型和继承是如何工作的。我基于以下代码: 我不知道如何继承属性值,我只能得到“方法”。我认为可能更合适的问题是在调用子对象时如何初始化父类的字段 根据上述网站,我写了如下内容:Javascript JS中的继承,继承属性和值,javascript,prototypal-inheritance,Javascript,Prototypal Inheritance,我是一个初学者,无法理解JavaScript中的原型和继承是如何工作的。我基于以下代码: 我不知道如何继承属性值,我只能得到“方法”。我认为可能更合适的问题是在调用子对象时如何初始化父类的字段 根据上述网站,我写了如下内容: function Person(name, surname) { this.name = name; this.surname = surname; } function Student(index) {
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
有没有办法创造一个学生,给他一个名字和姓氏
我是一个彻头彻尾的疯子,所以请像你向一个5岁的孩子解释一样解释。另外,我必须在JS中这样做,所以请不要推荐不同的方法,这对我没有帮助,谢谢:)你可以将
学生
构造函数更改为这个:
function Student(index, name, surname) {
this.index = index;
Person.call(this, name, surname);
}
获取可选参数,以便您可以使用附加参数调用
Person
,以设置自己的名称和姓氏属性。正确的方法是让您的子构造函数重复所需的参数
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();
这里真的不需要参数。原型将在属性值中用
未定义的初始化,这是完全合法的。否@伯吉:我不太明白这个评论,即使是在链接之后。你能详细说明一下吗?按“原样”,这个评论是错误的。我是说Student.prototype=newperson()
错误,应该是Student.prototype=Object.create(Person.prototype)代码>@Bergi:同意。混淆的是你的不是新人
,而你的意思是不是新人()
是的,括号可以省略,我主要关注新的
:-)也许下面的答案可以帮助你,还有一个处理构造函数参数的模式,但你可以在任何函数链中使用它:
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());