Jim12345 Posted February 27, 2014 Share Posted February 27, 2014 Hello, I have a question about prototypes. It seems to me I always encounter a new method being added to an object after the fact. For example this code below runs fine. <script>var GameObject = function(width, height) { this.x = Math.floor((Math.random() ) + 1); this.y = Math.floor((Math.random() ) + 1); this.width = width; this.height = height; this.car='AMC'; return this;};GameObject.prototype = { draw: function() { return (this.width); }};var n = new GameObject(2200,400);console.log(n.draw());</script> But what I want to do is right from the get go, have the method draw as part of the protoype, this I can't figure out. So what would the code look like? Thanks, Jim P. Link to comment Share on other sites More sharing options...
Don E Posted February 27, 2014 Share Posted February 27, 2014 Have you tried adding this.draw = function(){ // code to run here }; to the var GameObject function(object)? Link to comment Share on other sites More sharing options...
Jim12345 Posted February 27, 2014 Author Share Posted February 27, 2014 Don, I was trying to do this: draw = function(){ return (this.width); }; Instead of this: this.draw = function(){ return (this.width); }; Thanks, Jim P. Link to comment Share on other sites More sharing options...
Ingolme Posted February 27, 2014 Share Posted February 27, 2014 You need the this keyword unless you only want the method to be accessible from inside the object. var GameObject = function(...) { ... this.draw = function() { - }} Link to comment Share on other sites More sharing options...
Jim12345 Posted February 27, 2014 Author Share Posted February 27, 2014 Ah OK Thanks Foxy Mod so a private function not accessible to the outside world? Meaning you can't call it from outside it's scope? Link to comment Share on other sites More sharing options...
justsomeguy Posted February 27, 2014 Share Posted February 27, 2014 More or less, yeah. Link to comment Share on other sites More sharing options...
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