Skip to content

Instantly share code, notes, and snippets.

@yuka2py
Created October 24, 2012 00:45
Show Gist options
  • Save yuka2py/3943035 to your computer and use it in GitHub Desktop.
Save yuka2py/3943035 to your computer and use it in GitHub Desktop.
プロトタイプチェーンによる継承
プロトタイプチェーンによる継承で、基本だと思うんですが、16行目で Employee.prototype = new Person; ってやった時に、Personのコンストラクタが走るのが微妙です。
何か認識を間違っているのかしら?
//Personを作成
var Person = function(name) {
this.name = name;
};
//Personのメソッドを定義
Person.prototype.printName = function() {
document.write(this.name + "<br>");
};
//Employeeを作成
var Employee = function(name, salary) {
//Personのコンストラクタを呼び出し
Person.apply(this, [name]);
this.salary = salary;
};
//**POINT** PersonをPrototypeで継承
Employee.prototype = new Person;
//Employeeのメソッドを定義
Employee.prototype.printSalary = function() {
document.write(this.salary + "<br>");
};
//実行
var e = new Employee("Yuka2py", 24);
e.printName(); //Yuka2py
e.printSalary(); //24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment