おやおや、あなたはかなり多くのことを混乱させています。
function CarConstructor(){
this.speed=19; // in mph
this.make="Ford";
this.fillKph; // <-> This particular statement has no meaning.
//When you write this.fillKph without any assignment, it will be 'undefined'.
//Just because you have a function named 'fillKph' somewhere else,
//it doesn't mean it will get attached to this property.
}
試す、
var toyota = new Car();
alert(typeof toyota.fillKph); //will alert undefined.
fillKph関数は、グローバルスコープで、つまり「Window」オブジェクトのプロパティとして作成されます。
function fillKph(){
var me=this;
$("#kphdiv").html(me.speed*1.61);
}
それを修正するために、あなたはrezzifが提案したものをすることができます。最終的なコードは次のようになります
function Car()
{
this.speed=19; // in mph
this.make="Ford";
this.fillKph = function (){
$("#kphdiv").html(this.speed*1.61);
};
}
car1 = new Car();
car1.fillKph();
お気づきの方もいらっしゃると思いますが、ローカル変数内に「this」への参照を格納していません。なんで?このシナリオでは必要ありません。詳細については、こちらの詳細な回答をご覧ください。
多数のCarオブジェクトを作成する場合は、プロトタイプでfillKphメソッドを定義できます。
function Car()
{
this.speed=19; // in mph
this.make="Ford";
}
Car.prototype.fillKph = function fillKph() { $("#kphdiv").html(this.speed*1.61); };
car1 = new Car();
car1.fillKph();
編集:
あなたが次のようなことをするなら、
function CarConstructor(){
this.speed=19; // in mph
this.make="Ford";
this.fillKph = fillKph;
}
function fillKph(){
$("#kphdiv").html(me.speed*1.61);
}
car1 = new Car();
car1.fillKph(); //This will work as expected.
ただし、問題は、fillKphが「Window」スコープで定義されているため、次のように直接呼び出すことができることです。
fillKph(); //Calling it this way will break it as it won't get correct 'this'.
ポイントは、
alert(typeof fillKph); // alerts 'function' if you do it your way,
alert(typeof fillKph); // alerts 'undefined', if you do it the way I suggested, which is preferred in my opinion.