如何在 Javascript 中添加和调用来自构造函数的函数(使用 JQuery)

How to add and call functions from constructors in Javascript (uses JQuery)

本文关键字:函数 构造函数 使用 JQuery Javascript 添加 调用      更新时间:2023-09-26

我使用以下代码创建了一个对象文字。一切正常。

但是,当我尝试通过创建对象构造函数和相应的对象来重写对象文字,然后使用"点语法"执行该方法时,没有任何反应。我不清楚我做错了什么。下面的示例使用 JQuery。

谢谢。

对象文字(工作)

    <!DOCTYPE=HTML>
<meta chartset="UTF-8">
<title> whatever </title>
<script type="text/javascript"> </script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" charset="utf-8"></script>
<div id="theDiv"></div>
<style>
#theDiv{
position:absolute;
width:200px; 
height:200px; 
background:#f00; 
}
</style>


<script>
$(document).ready(function(){
var myObj  = {};
myObj.doThing =  function () {
$("#theDiv").toggle(3000);
  };

myObj.doThing();

});

</script>

带对象的构造函数(非工作)

<!DOCTYPE=HTML>
<meta chartset="UTF-8">
<title> whatever </title>
<script type="text/javascript"> </script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" charset="utf-8"></script>
<div id="theDiv"></div>
<style>
#theDiv{
position:absolute; 
width:200px; 
height:200px; 
background:#f00; 
}
</style>

<script>
 $(document).ready(function(){
function ConstructorExample (){
this.move =  function () {
$("#theDiv".toggle(3000);
  };
    };

var objExample = new ConstructorExample();

objExample.move();

});

</script>

第二个示例中存在语法错误。

更改此设置:

$("#theDiv".toggle(3000);

对此:

$("#theDiv").toggle(3000);

这不是为了解决你的问题(因为约瑟夫已经回答了),而是一个更好的做法供你参考:

更改自:

function ConstructorExample (){
  this.move =  function () {
    $("#theDiv").toggle(3000);
  };
};

更改为:

var ConstructorExample = function ConstructorExample () {
  this.node = $("#theDiv");
};
ConstructorExample.prototype.move = function () {
  if (!!this.node) {
    this.node.toggle(3000);
  }
};

的行为相同,但通过使用原型链,它不会在您每次启动对象时创建 move 函数(速度更快),并且可以进行原型继承。