哦,男孩,你混淆了很多事情。
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.