(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');
})()
Thay vì sử dụng cấu trúc dữ liệu tĩnh (lớp-type) định nghĩa, javascript sử dụng chức năng để tự động xây dựng nguyên mẫu cấu trúc dữ liệu. Đó là một bước nhảy vọt lớn bởi vì nó cho phép bạn xây dựng một cấu trúc khi bạn thu thập đủ ngữ cảnh để biết những gì bạn thực sự cần. Chuỗi nguyên mẫu là năng động là tốt, đó là một bước nhảy vọt lớn và tôi chỉ bắt đầu quấn quanh đầu của tôi.
Thay lời hơn, kiểm tra các nguồn sau 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
})()
Cảm ơn, bạn rất hào phóng như mọi khi :) – Tarik
Bạn chào đón Aaron, nếu bạn có bất kỳ nghi ngờ nào, đừng ngần ngại bình luận! – CMS