Oh boy, you are confusing a lot of things.
function CarConstructor(){ this.speed=19;
Try
var toyota = new Car(); alert(typeof toyota.fillKph);
The fillKph function is created in the global scope, i.e. as a property of the Window object.
function fillKph(){ var me=this; $("#kphdiv").html(me.speed*1.61); }
To fix this, you can do what rezzif suggested. Your last code will look like
function Car() { this.speed=19; // in mph this.make="Ford"; this.fillKph = function (){ $("#kphdiv").html(this.speed*1.61); }; } car1 = new Car(); car1.fillKph();
If you noticed, I did not keep a reference to 'this' inside a local variable. What for? There is no need for this scenario. To find out more, see my detailed answer here .
If you intend to create many Car objects, you can define the fillKph method on the prototype.
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();
EDIT:
If you do something like
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.
But the problem is that fillKph is defined in the Window area, so I can call it directly,
fillKph(); //Calling it this way will break it as it won't get correct 'this'.
Point,
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.