Renderer Posted May 5, 2020 Posted May 5, 2020 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!
therks Posted May 26, 2020 Posted May 26, 2020 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> My AutoIt Stuff | My Github
Noviceatthis Posted June 26, 2020 Posted June 26, 2020 (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; }()); Gianni 1
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now