(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');
})()
En lugar de utilizar la estructura de datos estática (de tipo clase) las definiciones, javascript utiliza funciones para crear dinámicamente prototipos estructura de datos. Eso es un gran salto porque te permite construir una estructura a medida que reúnes suficiente contexto para saber lo que realmente necesitas. La cadena de prototipos también es dinámica, lo cual es otro gran salto y estoy empezando a entenderlo.
En lugar de más palabras, marque la siguiente fuente Lucas:
(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
})()
Gracias, eres muy generoso como siempre :) – Tarik
De nada Aaron, si tienes alguna duda, ¡no dudes en comentar! – CMS