JAvascriptオブジェクト継承時の関数の定義
1187 ワード
高校のクラブで自測していたときに出会ったjavascriptの問題を、みんなと共有しました.
タイトル:
結果を聞く.テストの結果は
:プログラムエラーで、何も出力できません.
そしてst.study();外してから運行できるので、
変更後は次のようになります.
「張三豊学習」「張三豊移動」の関数を順次出力します.
どうしてこんなことになったの?具体的な原理は何ですか.大神の指導があることを望みます
タイトル:
function Person()
{
}
Person.prototype.move = function() { alert(this.name+" ");}
function Student(name)
{
this.name = name;
}
Student.prototype.study = function() { alert(this.name+" "); }
Student.prototype = new Person();
var st = new Student(" ");
st.study();
st.move();
結果を聞く.テストの結果は
:プログラムエラーで、何も出力できません.
そしてst.study();外してから運行できるので、
Student.prototype.study = function() { alert(this.name+" "); }
Student.prototype = new Person();
こちらでエラーが発生しました.あるオブジェクトがprototypeで別のオブジェクトを継承した後、prototypeで他の関数を追加することはできないと自分で結論した.関数を追加する場合はオブジェクト内部で実装されるはずですが、変更後は次のようになります.
function Person()
{
}
Person.prototype.move = function() { alert(this.name+" ");}
function Student(name)
{
this.name = name;
this.study=function(){
alert(this.name+" ");
}
}
Student.prototype = new Person();
var st = new Student(" ");
st.study();
st.move();
で実現「張三豊学習」「張三豊移動」の関数を順次出力します.
どうしてこんなことになったの?具体的な原理は何ですか.大神の指導があることを望みます