Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Простая задачка на идентичность объектов (https://javascript.ru/forum/misc/52059-prostaya-zadachka-na-identichnost-obektov.html)

Kosanna 02.12.2014 14:16

Простая задачка на идентичность объектов
 
Пожалуйста, подскажите, как решить вот такую задачку:

// Заставьте это работать
function Dummy() {
    // что-то тут нужно написать
}

Dummy.prototype.value = 'dummy';

Dummy.prototype.setValue = function (value) {
    this.value = value;
};

Dummy.prototype.getValue = function () {
    return this.value;
};

// Используем
var foo = new Dummy();
var bar = new Dummy();

bar.setValue(123);

// Тесты
console.log('-------------------');
console.info('foo === bar ->', foo === bar); // true
console.log('values:', [foo.getValue(), bar.getValue()]); // [123, 123]

// Bonus level
//baz = Dummy();
//console.info('baz === bar ->', baz === bar, baz.getValue()); // true, 123

nerv_ 02.12.2014 14:32

глубоко не вчитываясь:
1. Dummy - синглтон
2. либо переопределить valueOf

Kosanna 02.12.2014 14:51

Точно, синглтон, гениально! Спасибо!

krutoy 02.12.2014 15:01

Цитата:

Сообщение от Kosanna
console.info('foo === bar ->', foo === bar); // true

и при этом
var foo = new Dummy();
var bar = new Dummy();

Это невозможно в принципе. 2 разных объекта не могут быть одним и тем же. Насчет второго я не допер. Вы хотите, чтобы все экземпляры наследовали от класса, и меняли свойство класса, а не свое собственное?

Vlasenko Fedor 02.12.2014 22:48

// Заставьте это работать
  var Dummy = new function Dummy() {
      var instance;
      this.value = 'dummy';

      function Dummy() {
        if (!instance) instance = this;
        else return instance;

        Dummy.prototype.setValue = function (value) {
          this.value = value;
        };

        Dummy.prototype.getValue = function () {
          return this.value;
        };
      }
      return Dummy;
    }



    // Используем
  var foo = new Dummy();
  var bar = new Dummy();

  bar.setValue(123);

  // Тесты
  console.log('-------------------');
  console.info('foo === bar ->', foo === bar); // true
  console.log('values:', [foo.getValue(), bar.getValue()]); // [123, 123]
  // Bonus level
  baz = Dummy();
  console.info('baz === bar ->', baz === bar, baz.getValue()); // true, 123

рони 02.12.2014 23:12

Цитата:

Сообщение от Kosanna
// что-то тут нужно написать

:write:
// Заставьте это работать
function Dummy() {     // что-то тут нужно написать
    if (!arguments.callee.instance) {
        arguments.callee.instance = {
            setValue: this.setValue,
            getValue: this.getValue
        };
    }
    return arguments.callee.instance;

}

Dummy.prototype.value = 'dummy';

Dummy.prototype.setValue = function (value) {
    this.value = value;
};

Dummy.prototype.getValue = function () {
    return this.value;
};

// Используем
var foo = new Dummy();
var bar = new Dummy();

bar.setValue(123);

// Тесты

alert('foo === bar ->'+ (foo === bar)); // true
alert('values:'+ [foo.getValue(), bar.getValue()]); // [123, 123]

// Bonus level
baz = Dummy();
alert('baz === bar ->'+ [baz === bar, baz.getValue()]); // true, 123

Vlasenko Fedor 02.12.2014 23:56

Еще вариант
/// Заставьте это работать
function Dummy() {     // что-то тут нужно написать
    if (Dummy.prototype.instance) {
         return Dummy.prototype.instance;
    }
    Dummy.prototype.instance = this;

}

Dummy.prototype.value = 'dummy';

Dummy.prototype.setValue = function (value) {
    this.value = value;
};

Dummy.prototype.getValue = function () {
    return this.value;
};

// Используем
var foo = new Dummy();
var bar = new Dummy();

bar.setValue(123);

// Тесты

alert('foo === bar ->'+ (foo === bar)); // true
alert('values:'+ [foo.getValue(), bar.getValue()]); // [123, 123]

// Bonus level
baz = Dummy();
alert('baz === bar ->'+ [baz === bar, baz.getValue()]); // true, 123

и так
if (arguments.callee._singletonInstance) return arguments.callee._singletonInstance;
arguments.callee._singletonInstance = this;

jsnb 03.12.2014 03:53

// Заставьте это работать
function Dummy() {
    if (!Dummy.cache)  Dummy.cache = Object.create( Dummy.prototype );
    return Dummy.cache;
}

Dummy.prototype.value = 'dummy';

Dummy.prototype.setValue = function (value) {
    this.value = value;
};

Dummy.prototype.getValue = function () {
    return this.value;
};

// Используем
var foo = new Dummy();
var bar = new Dummy();

bar.setValue(123);

// Тесты
//console.log('-------------------');
console.info('foo === bar ->', foo === bar); // true
console.log('values:', [foo.getValue(), bar.getValue()]); // [123, 123]

// Bonus level
baz = Dummy();
console.info('baz === bar ->', baz === bar, baz.getValue()); // true, 123


Часовой пояс GMT +3, время: 13:03.