-1

In a snake game,

var snake;
snake.prototype.test = [];
snake.test.push(1);
console.log(snake.test[0]);

This does not return 1 in the console, anyone know why?can anyone help?

3
  • Does it report an error in the console instead? Commented Feb 23, 2014 at 14:28
  • 2
    From this example, snake doesn't have a prototype. Prototypes come from constructors. Commented Feb 23, 2014 at 14:31
  • 1
    snake.prototype.test = []; tries to create an Array in snake.prototype, which does not exist. Cannot read property 'prototype' of undefined - undefined here refers to snake's constructor. Commented Feb 23, 2014 at 14:47

3 Answers 3

1

Prototypes come from constructors. This shows how an instance has access to prototype members.

// create a constructor function
var Snake = function () {};

// add to the prototype of Snake
Snake.prototype.test = [];

// create a new instance of a Snake
var aSnake = new Snake();

// aSnake has access to test through the prototype chain
aSnake.test.push(1);
console.log(aSnake.test[0]);

// so do other snakes
var anotherSnake = new Snake();
console.log(anotherSnake.test[0]);

References

Sign up to request clarification or add additional context in comments.

1 Comment

The peril of this approach is that all snakes with that array object in their prototype share the exact same reference, which may not be what you want. If you want the snakes to have their own astray instances, just assign it in the constructor: this.test = [];
0

In your example, snake is not a constructor function nor has a new instance been created.

You might want to read up on object oriented JavaScript if you want to keep going down this path. For now, though, wouldn't it be simpler just to create a single object instance?

var snake = {};
snake.test = [];
snake.test.push(1);
console.log(snake.test[0]);

1 Comment

Cause I would like to create many snakes. That needs "prototype". (Found this somewhere from the internet)
0

You can create a simple object:

var snake = {
    test: []
};

snake.test.push(1);
console.log(snake.test[0]);

Thk :D

Comments