Jump to content

Javascript Object Constructor


Renderer
 Share

Recommended Posts

Hi there, 

I have recently started learning Javascript. Now I started working with Objects. I got some problems when I want to define my own Object with it's own methods. The code looks like this:

function Model(){

  var model = document.createElement("div");
  return model;
  
  this.append = function(parent) {
    
    document.getElementById(parent).appendChild(model);
  
  }
  
}

var farm = new Model();
farm.append("map");

The result should have looked like this: 

<div id="map">

  <div></div>
  
</div>

But instead the "map" container is empty. The result I wanted is, that the new element I created with the object Model() is appended to the "map" container by using the .append()  method. But instead it doesn't seam to happen like that. I do not get any error messages in the console even when using try - catch method. I have also tried the Object Prototypes like in the example bellow:

function Model() {
    var model = document.createElement("div");
    return model;
}

Model.prototype.append = function(parent) {
 
  document.getElementById(parent).appendChild(this);
  
}

var farm = new Model();
farm.append("map");

.. but the same story happen. The question is what am I doing wrong here? I am waiting for your answers.

Thanks in advance!

Link to comment
Share on other sites

  • 3 weeks later...

I'm an amateur with JavaScript objects myself, but I think this might be on the right track.

<div id="map"></div>

<script>
class Model {
    constructor() {
        this.model = document.createElement("div");
    }
    append(parent) {
        document.getElementById(parent).appendChild(this.model);
    }
}

var farm = new Model();
farm.append("map");
</script>

 

Link to comment
Share on other sites

  • 1 month later...

(Sorry I know I'm about 500 years late to the party here) If you really want to use pre-ES6 syntax

 

var Model = (function () {
    function Model(name) {
        this.model = document.createElement("div");
    }
    Model.prototype.append = function (parent) {
        document.getElementById(parent).appendChild(this.model);
    };
    return Model;
}());

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...