JavaScript 中的“this”如何工作?

2024-05-02

我知道还有其他几篇关于这个主题的帖子,但它们仍然让我感到困惑。

我已经包含了 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();

现在我知道该代码片段不起作用并且未正确构建。

“this”关键字引用了 id 为“kphdiv”的 dom 元素。

我的问题是处理这个问题的最佳方法是什么。

我见过一种方法,您将某个变量设置为等于此(绑定它),然后使用该变量来引用您的对象。例如:

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();

我也可以将 me 设为全局变量...我不知道。

我只是好奇是否有另一种/更好的方法。


哦,孩子,你混淆了很多事情。

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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript 中的“this”如何工作? 的相关文章

随机推荐