简体   繁体   中英

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

I have created an object literal using the code below. Everything works fine.

However, when I attempt to rewrite the object literal by creating an object constructor and a corresponding object, and then execute the method using the "dot syntax" nothing happens. I am unclear what I am doing wrong. The example below uses JQuery.

Thank you.

Object literal (working)

    <!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>

Constructor with object (non-working)

<!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>

You have syntax error in your second example.

Change this:

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

to this:

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

This is not to fix your problem (since Joseph has answered), but a better practise for your reference:

Change from:

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

Change to:

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

It behaves the same, but by using the prototyped chain, it do not create the move function every time you initiate the object (faster in speed), and it can be prototype inherited.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM