Javascript: Prototype object is not a function

133 Views Asked by At

Hopefully someone can help me with this code I have.

JavaScript:

function myFrame(id){
   if (id) {
      if (window === this) {
         return new myFrame(id);
      }
      this.e = document.getElementById(id);
      return this;
   } else {
      return "";
   }

}

myFrame.prototype = {
    math: function () {
        alert(1 + 1);
    },
    hide: function () {
       this.e.style.display = 'none';
       return this;
    }
}

HTML:

<p id="hideParagraph">Hide Paragraph</p>
<input type="button" name="math" onclick="hide()" value="Hide Paragraph" />
<input type="button" name="math" onclick="math()" value="Alert Math" /> 


<script type="text/javascript">

    function math() {
        myFrame("body").math();
    }

    function hide() {
        myFrame("hideParagraph").hide();
    }

</script>

The code above works fine but I want to know is there a way not to specify an element.

For example I need to specify "body" or some other string value in order for this code to work, else I get a "is not a function" error message

myFrame("body").math();

Is there a way for me to have this code like :

myFrame().math();

And also still use the "hide" method like:

myFrame("hideParagraph").hide();

Any help is much appreciated!

3

There are 3 best solutions below

1
On

The problem is your

return "";

Try:

return this;
0
On

Maybe this will help you understand your problem:

function Thing(val) {
  this.val = val;  
};

Thing.prototype.alert = function() {
  alert(this.val);  
};

function start(val) {
  return new Thing(val);
}

start("Hi").alert();

You want a class with the alert method and then create a new instance of that class in an outside function.

There are probably many ways to do this. With this setup you can call start multiple times.

0
On

The problem here is your return values.

When you call myFrame("body"), the window === this inside your function is true so then new myrFrame('body') is called. When that happens, you return this;. the newly created object. It's this object that contains the .math() and .hide() methods on its prototype.

myFrame().math(); on the other hand. myFrame() fails the if(id) check, so it just returns ''. A blank string. Not a myFrame() object. Strings don't have a .math() method.

You need to tweak your myFrame function like so:

function myFrame(id){
    // Determine whether we called 'myFrame()` or 'new myFrame()'
    // In "use strict"; (strict mode), do `if(!this)`
    if (window === this) {
        return new myFrame(id);
    }
    else{
        // In here, this is our new myFrame object
        if(id){
            this.e = document.getElementById(id);
        }

        // This return statement isn't actually needed
        // return this;
    }
}

Make sure it always returns an object regardless of what parameter you pass.