2017-05-18 17 views
0

Object.create(functionname.prototype)と新しいStudent()コンストラクタコールの違いは何ですか?継承を伴うJavascriptプロトタイプオブジェクト

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 

私はその後、私はStudent`sオブジェクトのプロパティにアクセスすることができない第一の方法を使用しますが、私はそれができる第二の方法を使用して、違いは何ですか。私は両方の方法が同じだと思う...それは間違っていますか?

答えて

1

std.nameにアクセスできない理由は、UniversityStudentコンストラクタからStudentコンストラクタを実行していないためです。

あなたはこのラインで正常学生を拡張します:

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

しかし、あなたはそれをインスタンス化するときには、ドキュメントを見てみましょう。この

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

同様Student.call(this, name)

を行う必要がありますここに:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

+0

ありがとうございました......: –

+0

MDNの継承とプロトタイプチェーンのページをチェックアウトしてください。プロトタイプモデルの多くの欠点を説明しています。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain –