Skip to content

Commit 42f64b7

Browse files
Some concepts about JS object.
1 parent dd5b5a5 commit 42f64b7

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

about_objects.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// About objects.
2+
3+
var rabbit = {};
4+
5+
rabbit.speak = function(line) {
6+
console.log("The rabbit says '" + line + "'");
7+
};
8+
rabbit.speak("I'm alive.");
9+
10+
// Special variable this.
11+
function speak(line) {
12+
console.log("The " + this.type + " rabbit says '" + line + "'");
13+
}
14+
15+
var whiteRabbit = {type: "white", speak: speak};
16+
var fatRabbit = {type: "fat", speak: speak};
17+
18+
whiteRabbit.speak("Oh my ears and whiskers, how late it's getting!");
19+
fatRabbit.speak("I could sure use a carrot right now.");
20+
21+
speak.apply(fatRabbit, ["Burp!"]);
22+
speak.call({type: "old"}, "私は日本語を話すことができます。");
23+
24+
var empty = {};
25+
console.log(empty.toString);
26+
console.log(empty.toString());
27+
28+
// Creating an object with specific prototype.
29+
var protoRabbit = {
30+
speak: function(line) {
31+
console.log("The " + this.type + " rabbit says '" + line + "'");
32+
}
33+
};
34+
35+
var killerRabbit = Object.create(protoRabbit);
36+
killerRabbit.type = "killer";
37+
killerRabbit.speak("SKREEEE!");
38+
39+
// Object constructor.
40+
41+
function Rabbit(type) {
42+
this.type = type;
43+
}
44+
45+
var killerRabbit = new Rabbit("killer");
46+
var blackRabbit = new Rabbit("black");
47+
48+
console.log(blackRabbit.type);
49+
50+
Rabbit.prototype.speak = function(line) {
51+
console.log("The " + this.type + " rabbit says '" + line + "'");
52+
};
53+
blackRabbit.speak("Doom...");
54+
55+
// Overriding an object's derived properties.
56+
57+
Rabbit.prototype.teeth = "small";
58+
console.log(killerRabbit.teeth);
59+
killerRabbit.teeth = "long, sharp, and bloody";
60+
console.log(killerRabbit.teeth);
61+
62+
console.log([1, 2].toString());
63+
console.log(([1, 2].toString()).length);
64+

0 commit comments

Comments
 (0)