Get si set pe proprietati in Javascript

Lucram cu un framework de MVVM pe javascript , asemanator cu knockout ( ok, da – am trecut la angular 2 ) . Si nu intelegeam cine imi seta o proprietate pe null. Adica aveam asa ceva :

var person = {
Name : “Ignat”
}

 

iar cineva din cod( adica eu…), dupa citeva clickuri pe interfata( 3 combo-uri in cascada ) , cindva, imi seta Name la null – si nu intelegeam cind .

Solutia ? Get/set in javascript – modificat din Name in name si define property:

var person = {name : “Ignat”};

Object.defineProperty( person , 'Name',
 {get : function(){ return name; },
set : function( value ){ this.name = value; }
} ); 

Asa ca am pus un breakpoint in debugger in browser (F12) pe set – si voila! doar un copy paste gresit – faceam bind la niste valori si setam ce nu trebuia…

Apoi am sters codul si am revenit la initial( asta pentru ca nu aveam chef de linii in plus)

var person = {
Name : “Ignat”
}

 

Morala 1: Se poate si in javascript sa ai get/set – doar ca nu merita …

Morala 2: se poate face un tt cu asta – care , in functie de un parametru, sa iti scrie fie varianta simpla, fie cea cu defineProperty – in functie daca vrei sa faci debug sau nu…

2 thoughts on “Get si set pe proprietati in Javascript

  1. I first thought of using something like a C# data breakpoint, only there is no such thing in Chrome or other browsers. Then I thought of object.watch (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch), only it is not implemented in all browsers and likely it will be obsolete soon. In the end, setters/getters were the solution, but I found a nice answer about how you can encapsulate it, creating basically data breakpoints: http://stackoverflow.com/questions/11618278/how-to-break-on-property-change-in-chrome#answer-11658693

Leave a Reply

Your email address will not be published. Required fields are marked *