我知道关于这个话题还有其他一些帖子,但它们仍让我感到困惑.
我已经包含了jQuery和所有内容,我有一个像这个例子的简单的javascript类:
function CarConstructor(){
this.speed=19; // in mph
this.make="Ford";
this.fillKph=fillKph;
}
function fillKph(){
$("#kphdiv").html(this.speed*1.61);
}
car1 = new CarConstructor();
car1.fillKph();
Run Code Online (Sandbox Code Playgroud)
现在我知道该代码段不起作用,并且没有正确构建.
"this"关键字引用了我的dom元素,其id为"kphdiv".
我的问题是处理这个问题的最佳方法是什么.
我见过一种方法,你设置一些等于此的变量(绑定它),然后使用该变量来引用你的对象.例如:
function CarConstructor(){
this.speed=19; // in mph
this.make="Ford";
this.fillKph=fillKph;
}
function fillKph(){
var me=this;
$("#kphdiv").html(me.speed*1.61);
}
car1 = new CarConstructor();
car1.fillKph();
Run Code Online (Sandbox Code Playgroud)
我也可以让我成为一个全球变量...我不知道.
如果有另一种/更好的方式,我只是好奇.
Sol*_*ogi 10
哦,孩子,你混淆了很多东西.
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.
}
Run Code Online (Sandbox Code Playgroud)
尝试,
var toyota = new Car();
alert(typeof toyota.fillKph); //will alert undefined.
Run Code Online (Sandbox Code Playgroud)
fillKph函数在全局范围内创建,即作为'Window'对象的属性.
function fillKph(){
var me=this;
$("#kphdiv").html(me.speed*1.61);
}
Run Code Online (Sandbox Code Playgroud)
要修复它,你可以使用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();
Run Code Online (Sandbox Code Playgroud)
如果你注意到,我没有在局部变量中存储对'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();
Run Code Online (Sandbox Code Playgroud)
编辑:
如果你做的事情,
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.
Run Code Online (Sandbox Code Playgroud)
但问题是fillKph是在'Window'范围内定义的,所以我可以直接调用它,就像
fillKph(); //Calling it this way will break it as it won't get correct 'this'.
Run Code Online (Sandbox Code Playgroud)
点是,
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.
Run Code Online (Sandbox Code Playgroud)