forked from chuanxshi/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsugar-method.html
More file actions
37 lines (34 loc) · 815 Bytes
/
sugar-method.html
File metadata and controls
37 lines (34 loc) · 815 Bytes
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
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: method() Method
Description: adding convenient functionality to a language
*/
if (typeof Function.prototype.method !== "function") {
Function.prototype.method = function (name, implementation) {
this.prototype[name] = implementation;
return this;
};
}
var Person = function (name) {
this.name = name;
}.
method('getName',
function () {
return this.name;
}).
method('setName', function (name) {
this.name = name;
return this;
});
var a = new Person('Adam');
console.log(a.getName()); // 'Adam'
console.log(a.setName('Eve').getName()); // 'Eve'
</script>
</body>
</html>