· 8 years ago · Apr 10, 2018, 07:24 PM
1// author: abaqueiro at gmail.com
2// pasando de java a javascript
3//en java:
4
5class Punto2D {
6 private double _x = 0;
7 private double _y = 0;
8
9 public double getX(){
10 return _x;
11 }
12
13 public double getY(){
14 return _y;
15 }
16
17 public void setX( double newX ){
18 _x = newX;
19 }
20
21 public void setY( double newY ){
22 _y = newY;
23 }
24}
25
26//¿como implemento esto en javascript?
27//hay 2 grandes aproximaciones (a y b)
28
29//en a
30// sacrificas la privacidad (sin prototype)
31// con esperanzas de poder implementar herencia
32
33//a.1)
34Punto2D = function(){
35 this._x = 0;
36 this._y = 0;
37}
38
39Punto2D.getX = function(){
40 return this._x;
41}
42
43Punto2D.getY = function(){
44 return this._y;
45}
46
47Punto2D.setX = function( newX ){
48 this._x = newX;
49}
50
51Punto2D.setY = function( newY ){
52 this._y = newY;
53}
54
55//a.2) equivalente a a.1
56Punto2D = function(){
57 this._x = 0;
58 this._y = 0;
59
60 this.getX = function(){
61 return this._x;
62 }
63
64 this.getY = function(){
65 return this._y;
66 }
67
68 this.setX = function( newX ){
69 this._x = newX;
70 }
71
72 this.setY = function( newY ){
73 this._y = newY;
74 }
75}
76
77//a.3) equivalente usando prototype
78Punto2D = function(){
79 this._x = 0;
80 this._y = 0;
81}
82
83Punto2D.prototype.getX = function(){
84 return this._x;
85}
86
87Punto2D.prototype.getY = function(){
88 return this._y;
89}
90
91Punto2D.prototype.setX = function( newX ){
92 this._x = newX;
93}
94
95Punto2D.prototype.setY = function( newY ){
96 this._y = newY;
97}
98
99/*
100NOTA SOBRE HERENCIA
101respecto a la herencia, se puede implementar asÃ:
102*/
103Punto3D = function(){
104 new Punto2D();
105 this._z = 0;
106}
107Punto3D.getZ = function(){
108 return this._z;
109}
110Punto3D.setZ = function( newZ ){
111 this._z = newZ;
112}
113/*
114FIN DE NOTA SOBRE HERENCIA
115*/
116
117
118//la otra forma, la opción b, con private
119
120//b.1)
121Punto2D = function(){
122
123 // estas son privadas
124 var _x;
125 var _y;
126
127 this.getX = function(){
128 return _x;
129 }
130
131 this.getY = function(){
132 return _y;
133 }
134
135 this.setX = function( newX ){
136 _x = newX;
137 }
138
139 this.setY = function( newY ){
140 _y = newY;
141 }
142}