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?
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]);
this.test = [];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]);
snake.prototype.test = [];tries to create an Array insnake.prototype, which does not exist.Cannot read property 'prototype' of undefined- undefined here refers to snake's constructor.