哦,孩子,你混淆了很多事情。
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.
}
Try,
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”的引用存储在局部变量中。为什么?在这种情况下没有必要。要了解更多信息,请参阅我的详细答案在这里 https://stackoverflow.com/questions/1007340/javascript-function-aliasing-doesnt-seem-to-work/1162192#1162192.
如果要创建大量 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();
EDIT:
如果你做类似的事情,
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.