forked from loaialaddien/javascriptNotes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
method chaining.js
122 lines (93 loc) · 2.58 KB
/
method chaining.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// What is Method Chaining?
// is a technique that can be used to simplify code in scenarios that involve calling multiple functions on the same object consecutively.
// This is an example of how you can use method chaining when using jQuery.
// - mn el a5er law 3ndy object mo3yn 3awz atb2 3leh kza function .. fa bdl el kza line ely hktbhom la2 a3ml chaining a7sn .
// ex:
$('#my-div').css('background', 'blue').height(100).fadeIn(200);
// Implementing Method Chaining
// Let's rewrite the Kitten class with the ability to chain methods :
// define the class
var Kitten = function() {
this.name = 'Garfield';
this.color = 'brown';
this.gender = 'male';
};
Kitten.prototype.setName = function(name) {
this.name = name;
return this;
};
Kitten.prototype.setColor = function(color) {
this.color = color;
return this;
};
Kitten.prototype.setGender = function(gender) {
this.gender = gender;
return this;
};
Kitten.prototype.save = function() {
console.log(
'saving ' + this.name + ', the ' +
this.color + ' ' + this.gender + ' kitten...'
);
// save to database here...
return this;
};
// --------------------------------
// WITHOUT CHAINING
var bob = new Kitten();
bob.setName('Bob');
bob.setColor('black');
bob.setGender('male');
bob.save();
// OUTPUT:
// > saving Bob, the black male kitten...
///////////////////
// WITH CHAINING
new Kitten()
.setName('Bob')
.setColor('black')
.setGender('male')
.save();
// OUTPUT:
// > saving Bob, the black male kitten...
class Cat {
constructor(name, age, color) {
this.name = name;
this.age = age;
this.color = color;
}
setGender(gender) {
this.gender = gender;
return this;
}
setName(name) {
this.name = name;
return this;
}
setColor(color) {
this.color = color;
return this;
}
}
let y = new Cat();
y.setColor("blue").setGender("male").setName("hamada");
// Cat { name: "hamada", age: undefined, color: "blue", gender: "male" }
class Animal {
constructor(name, gender) {
this.name = name;
this.gender = gender;
}
changeName(name) {
this.name = name;
return this;
}
setAge(age) {
this.age = age;
return this;
}
}
let lion = new Animal("fluffy", "male");
lion.changeName("Asd aL ghaba");
lion.setAge(12);
let giraffe = new Animal("soa3d", "female");
giraffe.changeName("fatma").setAge(12);