Jump to content

Prototypes in Javascript


Jim12345

Recommended Posts

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

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

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
×
×
  • Create New...