JavaScript的OOP,從這裏可以理解與掌握,今後的應用就得靠自己了。
定義:
// Constructor function Kid (name) { // Private var idol = "Paris Hilton"; // Privileged this.getIdol = function () { return idol; }; // Public this.name = name; } // Public Kid.prototype.getName = function () { return this.name; }; // Static property Kid.town = "South Park";
-------------------------------
驗證上面的類:
// Create a new instance var cartman = new Kid("Cartman"); // Access private property cartman.idol; // undefined // Access privileged method cartman.getIdol(); // "Paris Hilton" // Access public property cartman.name; // "Cartman" // Access public method cartman.getName(); // "Cartman" // Access static property on an instance cartman.town; // undefined // Access static property on the constructor object Kid.town; // "South Park"
參考:
http://robertnyman.com/2008/10/14/javascript-how-to-get-private-privileged-public-and-static-members-properties-and-methods/