0

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>

2 Answers 2

1

You have syntax error in your second example.

Change this:

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

to this:

$("#theDiv").toggle(3000);
Sign up to request clarification or add additional context in comments.

1 Comment

I am very embarrassed. Thank you.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.