Reputation:
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?
Upvotes: -1
Views: 91
Reputation: 86
You can create a simple object:
var snake = {
test: []
};
snake.test.push(1);
console.log(snake.test[0]);
Thk :D
Upvotes: 0
Reputation: 2417
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]);
Upvotes: 1
Reputation: 46183
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]);
Upvotes: 0