user1293029
user1293029

Reputation:

Javascript array as an prototype (not array.prototype)

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

Answers (3)

Breno Polanski
Breno Polanski

Reputation: 86

You can create a simple object:

var snake = {
    test: []
};

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

Thk :D

Upvotes: 0

reergymerej
reergymerej

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]);

References

Upvotes: 1

Platinum Azure
Platinum Azure

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

Related Questions