K
K
Kolya2014-05-27 16:24:26
JavaScript
Kolya, 2014-05-27 16:24:26

JavaScript how to get a variable from one class to another?

Hello, this is the question ...
I am writing a "snake" game in JS, I have 2 classes in separate files, a snake class and a cell class with food, in the snake class I need to compare the coordinates of the snake's head and the cell with food, in what way can in snake class get variables containing cell coordinates from food cell class?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Lesnykh, 2014-05-27
@Aliance

Direct call:

// 1.js
var someObj = {
    value: 123
};

// 2.js
var anotherObj = {
   move: function() {
       alert(someObj.value);
   }
};

Or through dependency injection when initializing objects, depending on how the application logic is built. I like this option better:
// 1.js
function someObj() {}

someObj.prototype.init = function() {
    this.value = 123;
}

// 2.js
function anotherObj() {}

anotherObj.prototype.init = function(dependentObj) {
    this.someObj = dependentObj;
    alert(this.someObj.value);
}

// index.html
var obj1 = new someObj();
obj1.init();
var obj2 = new anotherObj();
obj2.init(obj1);

K
KOLANICH, 2014-05-27
@KOLANICH

i have 2 classes

There are no classes in JS.
And properties can be obtained as usual, through a dot.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question