Search

12/15/2008

Ajaxian » More JavaScript Inheritance; Prototypes vs. Closures

Ajaxian » More JavaScript Inheritance; Prototypes vs. Closures
JavaScript Inheritance via Prototypes and Closures | ruzee.com - Steffen Rusitschka
Prototype-based


var A = function(){}; // This is the constructor of "A"
A.prototype.value = 1;
A.prototype.test = function() { alert(this.value); }
var a = new A(); // create an instance of A
alert(a.value); // => 1
alert(a.test()); // => 1

Closure-based

var C = function() {
// a private function
var print = function(msg) {
alert(msg);
};
this.value = 1;
this.test = function() {
print(this.value); // calls our private function
};
};
var c = new C();
alert(c.value); // => 1
alert(c.test()); // => 1

沒有留言: