具有继承的Javascript Prototype对象

时间:2017-05-18 17:24:40

标签: javascript

Object.create(functionname.prototype)与新的Student()构造函数调用之间有什么不同。

function Student(name){
    this.name = name;
}
 function UniversityStudent(id){
    this.id= id;
}


// 1st way
UniversityStudent.prototype = Object.create(Student.prototype);
var std = new UniversityStudent(123);
// but I cannot access std.name why ?

// 2nd way
UniversityStudent.prototype = new Student("Lasith Malinga");
var std1 = new UniversityStudent(123);
// When I use std1.name now then it can

当我使用第一种方式时,我无法访问学生的对象属性,但我可以使用第二种方式,有什么区别。我认为两种方式都一样......是不是错了?

1 个答案:

答案 0 :(得分:2)

您无法访问std.name的原因是您没有使用Student构造函数中的UniversityStudent构造函数。

您确实使用此行成功扩展了学生:

UniversityStudent.prototype = Object.create(Student.prototype);

但是当你实例化它时,你必须做Student.call(this, name)

喜欢这个

function Student(name){
this.name = name;
}
function UniversityStudent(id, name){
  Student.call(this, name);
  this.id= id;
}

请查看此处的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create