简体   繁体   中英

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?

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

You can create a simple object:

var snake = {
    test: []
};

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

Thk :D

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM