(function(){
function Mankind() {
this.name = "joe";
}
function Person(){
this.Run = function(fromWhat){
alert(this.name + ' runs from ' + fromWhat + '!');
}
}
Person.prototype = new Mankind;
var dude = new Person;
dude.Run('bear');
})()
Anstatt statische Datenstrukturdefinitionen (Klassentyp) zu verwenden, verwendet Javascript Funktionen, um dynamisch Datenstrukturprototypen zu erstellen. Das ist ein großer Sprung, weil es Ihnen erlaubt, eine Struktur zu bauen, wie Sie sammeln genug Kontext zu wissen, was Sie wirklich brauchen. Die Prototypenkette ist ebenfalls dynamisch, was ein weiterer großer Sprung ist, und ich fange gerade erst an, mir darüber klar zu werden.
Anstelle von mehr Worten, schauen Sie sich die folgende Quelle an: Luke:
(function(){
// prototype chaining example
function f1(){this.foo = "foo"}
function f2(){this.bar = "bar"}
function f3(){this.bat = "bat"}
f2.prototype = new f1();
f3.prototype = new f2();
var a = new f1;
var b = new f2;
var c = new f3;
// state is inherited
var member_list = [
a.foo, // "foo"
a.bar, // undefined
a.bat, // undefined
b.foo, // "foo"
b.bar, // "bar"
b.bat, // undefined
c.foo, // "foo"
c.bar, // "bar"
c.bat // "bat"
];
// prototypes are chained
var instanceof_list = [
a instanceof f1, // true
a instanceof f2, // false
a instanceof f3, // false
b instanceof f1, // true
b instanceof f2, // true
b instanceof f3, // false
c instanceof f1, // true
c instanceof f2, // true
c instanceof f3 // true
];
// try to break chain
function f4(){this.fu = "fu"}
f2.prototype = new f4;
// state is preserved
var member_list2 = [
a.foo, // "foo"
a.bar, // undefined
a.bat, // undefined
b.foo, // "foo"
b.bar, // "bar"
b.bat, // undefined
c.foo, // "foo"
c.bar, // "bar"
c.bat // "bat"
];
// chain not broken, but link is removed
var instanceof_list2 = [
a instanceof f1, // true
a instanceof f2, // false
a instanceof f3, // false
b instanceof f1, // true
b instanceof f2, // false
b instanceof f3, // false
c instanceof f1, // true
c instanceof f2, // false
c instanceof f3 // true
];
// no new link is added
var instanceof_list3 = [
a instanceof f4, // false
b instanceof f4, // false
c instanceof f4 // false
];
debugger
})()