-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprototype_property.js
More file actions
120 lines (90 loc) · 2.27 KB
/
prototype_property.js
File metadata and controls
120 lines (90 loc) · 2.27 KB
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
alert = console.log
{
let animal = {
eats: true
};
function Rabbit(name) {
this.name = name;
}
Rabbit.prototype = animal;
let rabbit = new Rabbit("White Rabbit"); // rabbit.__proto__ == animal
alert( rabbit.eats ); // true
}
{
function Rabbit() {}
// by default:
// Rabbit.prototype = { constructor: Rabbit }
alert(Rabbit.prototype)
alert(Rabbit.prototype.constructor)
alert(Rabbit.prototype.constructor == Rabbit ); // true
}
{
function Rabbit() {}
// by default:
// Rabbit.prototype = { constructor: Rabbit }
let rabbit = new Rabbit(); // inherits from {constructor: Rabbit}
alert(rabbit.constructor == Rabbit); // true (from prototype)
}
{
function Rabbit(name) {
this.name = name;
alert(name);
}
let rabbit = new Rabbit("White Rabbit");
let rabbit2 = new rabbit.constructor("Black Rabbit");
}
{
function Rabbit() {}
Rabbit.prototype = {
jumps: true,
constructor: Rabbit
};
let rabbit = new Rabbit();
alert(rabbit.constructor === Rabbit); // false
let new_rabbit = rabbit.constructor()
alert(rabbit)
alert(new_rabbit)
alert(rabbit == new_rabbit)
}
{
let arr = [1, 2, 3];
// it inherits from Array.prototype?
alert( arr.__proto__ === Array.prototype ); // true
// then from Object.prototype?
alert( arr.__proto__.__proto__ === Object.prototype ); // true
// and null on the top.
alert( arr.__proto__.__proto__.__proto__ ); // null
}
{
function f() {}
alert(f.__proto__ == Function.prototype); // true
alert(f.__proto__.__proto__ == Object.prototype); // true, inherit from objects
}
{
String.prototype.show = function() {
alert(this);
};
"BOOM!".show(); // BOOM!
}
{
if (!String.prototype.repeat) { // if there's no such method
// add it to the prototype
String.prototype.repeat = function(n) {
// repeat the string n times
// actually, the code should be a little bit more complex than that
// (the full algorithm is in the specification)
// but even an imperfect polyfill is often considered good enough for use
return new Array(n + 1).join(this);
};
}
alert( "La".repeat(3) ); // LaLaLa
}
{
let obj = {
0: "Hello",
1: "world!",
length: 2,
};
obj.join = Array.prototype.join;
alert( obj.join(',') ); // Hello,world!
}