2014-03-30 65 views
0

我是初学者,无法理解原型和继承在JavaScript中是如何工作的。我基于这里的代码: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance 我无法弄清楚如何继承属性值,我只能得到“方法”。我认为也许更合适的问题是如何在调用子对象时启动父类的字段?JS中的继承,继承属性和值

按照提到的网站,我写了这样的事情:

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

也许下面的回答可以帮助你,也有与构造函数的参数有关系的模式,但你可以用在任何功能链:http://stackoverflow.com/a/16063711/1641941 – HMR

回答

0

您可以更改Student构造这一个:

function Student(index, name, surname) { 
    this.index = index; 
    Person.call(this, name, surname); 
} 

call采用可选参数所以你可以调用Person和其他参数来设置名字和姓氏自己的属性。

1

正确的做法是让您的子构造函数重复所需的参数。

function Student(index, name, surname) { 
    this.index = index; 
    Person.call(this, name, surname); 
} 

var s = new Student ('89890', 'Jan', 'Kowalski'); 

Btw。这

Student.prototype = new Osoba(); 

肯定是一个错字,而不是有

Student.prototype = new Person(); 

,你真的不需要这里的参数。原型将以undefined的属性值进行初始化,这是完全合法的。

+0

没有, [这不是'新人'](http://stackoverflow.com/questions/12592913/what-is-the-reason-to-use-the-new-keyword-here)! – Bergi

+0

@Bergi:即使在链接之后,我也不太明白这一点。你能详细说明吗?采取“原样”,这个评论是错误的。 –

+0

我在说'Student.prototype = new Person();'是错的,应该是'Student.prototype = Object.create(Person.prototype);' – Bergi

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