(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');
})()
Au lieu d'utiliser la structure de données statique des définitions (classe de type), javascript utilise des fonctions de construire dynamiquement des prototypes de structure de données. C'est un grand saut car cela vous permet de construire une structure en rassemblant suffisamment de contexte pour savoir ce dont vous avez réellement besoin. La chaîne de prototypes est également dynamique, ce qui constitue un autre grand pas en avant et je commence tout juste à en faire le tour.
Au lieu de plusieurs mots, vérifiez la source suivante Luc:
(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
})()
Merci, vous êtes très généreux comme toujours :) – Tarik
De rien Aaron, si vous avez des doutes, n'hésitez pas à commenter! – CMS