var SomeGlobalObject = function(){ this.prop1 = 1; this.prop2 = 2; } SomeGlobalObject.prototype.move(){ /* вот здесь можно ли определить какой именно объект (obj1 или obj2) в настоящее время использует метод move? Я остановился на том, чтобы добавить этим объектам свойство name и по его значению их идентифицировать. Как по-другому можно определить имя объекта? */ } var obj1 = new SomeGlobalObject(); var obj2 = new SomeGlobalObject(); obj1.move(); obj2.move(); 
  • @VladD, thanks. Simple as that. I was confused by the fact that console.log (this) returns "SomeGlobalObject", and your test works! I will explain about your question - the move method contains a large amount of code common to all objects. obj1, obj2, obj3 use the same code for their movement, the only difference is in interaction with OTHER objects. For this and need to distinguish them. Transform your comment into response - Deus
  • @Deus: Please! - VladD

1 answer 1

This check should come up:

 if (this === obj1) { ... 

In general, explain why this is for you. Isn't it easier to set each of the objects with its own function move ?


If you have a lot of common code, it may be better to do this:

 SomeGlobalObject.prototype.move = function(){ /* здесь код, бегущий в общем случае */ } var obj1 = new SomeGlobalObject(); obj1.commonMove = obj1.move; obj1.move = function() { // делаем то, что нужно только obj1 this.commonMove(); // вызываем "общий" move } 

Or so:

 SomeGlobalObject.prototype.commonMove = function(){ /* здесь код, бегущий в общем случае */ } SomeGlobalObject.prototype.move = function(){ this.move(); // поведение по умолчанию } var obj1 = new SomeGlobalObject(); obj1.move = function() { // делаем то, что нужно только obj1 this.commonMove(); // вызываем "общий" move }