0

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

但是,当我尝试通过创建对象构造函数和相应的对象来重写对象字面量,然后使用“点语法”执行该方法时,什么也没有发生。我不清楚我做错了什么。下面的示例使用 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>
4

2 回答 2

1

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

改变这个:

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

对此:

$("#theDiv").toggle(3000);
于 2012-06-13T02:18:33.160 回答
1

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

更改自:

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

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

于 2012-06-13T02:38:13.140 回答