Ciao a tutti,
Sul libro che sto leggendo ci sono 2 codici simili ma non riesco a capire perché il testo li definisce tali, a me sembrano assolutamente identici. L'output che ottengo è identico!
1° CODICE
2° CODICEcodice:var switchProto = { isOn: function isOn() { return this.state; }, toggle: function toggle() { this.state = !this.state; return this; }, meta: { name: 'Light switch' }, state: false }, switch1 = $.extend({}, switchProto), switch2 = $.extend({}, switchProto); test('Prototype clones.', function () { switch1.isOn.isShared = true; ok(!switch2.isShared, 'Methods are copied for each instance, not shared.' ); ok(switch1.toggle().isOn(), '.toggle() works.' ); ok(!switch2.isOn(), 'instance safe.' ); switch2.meta.name = 'Breaker switch'; console.log(switch1.meta.name); switch2.meta = { name: 'Power switch' }; console.log(switch1.meta.name); });
DIFFERENZA TRA I DUE SCRIPTcodice:var switchProto = { isOn: function isOn() { return this.state; }, toggle: function toggle() { this.state = !this.state; return this; }, meta: { name: 'Light switch' }, state: false }, switch1 = Object.create(switchProto), switch2 = Object.create(switchProto); test('Prototype clones.', function () { switch1.isOn.isShared = true; ok(!switch2.isShared, 'Methods are copied for each instance, not shared.' ); ok(switch1.toggle().isOn(), '.toggle() works.' ); ok(!switch2.isOn(), 'instance safe.' ); switch2.meta.name = 'Breaker switch'; console.log(switch1.meta.name); switch2.meta = { name: 'Power switch' }; console.log(switch1.meta.name); });
1° CODICE
2° CODICEcodice:switch1 = Object.create(switchProto), switch2 = Object.create(switchProto);
OUTPUT IDENTICO DEI 2 SCRIPTcodice:switch1 = $.extend({}, switchProto), switch2 = $.extend({}, switchProto);
codice:"TEST SUPERATO: ok( true , Methods are copied for each instance, not shared. )" "TEST SUPERATO: ok( true , .toggle() works. )" "TEST SUPERATO: ok( true , instance safe. )" "Breaker switch" "Breaker switch"![]()


Rispondi quotando
