-2

Trying to create an element with some custom properties

function x(){
    var f=document.createElement("div");
    this.name="monkey";
    return f;
}
x.prototype.myFunction=function(){
    alert(arguments[0]+this.name);
};
var c=new x();
c.myFunction("hello");

The browser says that c.myFunction is not a function

Deduplicator
  • 44,692
  • 7
  • 66
  • 118

2 Answers2

5

You are returning an HTML element in your function, so c will have a reference to the element and not your object.

Remove return f; and you'll get your expected output of an alert box containing 'hellomonkey'

Matt Cain
  • 5,638
  • 3
  • 36
  • 45
0

Is this ok for you?

function x(){
  var f=document.createElement("div");
  this.name="monkey";

  this.myFunction=function(){
    alert(arguments[0]+this.name);
  };

  this.returnDiv = function() {
    return f;
  }

  return this;
}
var c=new x();
c.myFunction("hello");
Filipe Melo
  • 558
  • 5
  • 10