首页 > 代码库 > JavaScript Patterns 5.6 Static Members
JavaScript Patterns 5.6 Static Members
Public Static Members
// constructorvar Gadget = function (price) { this.price = price;};// a static methodGadget.isShiny = function () { // this always works var msg = "you bet"; // Checking if the static method is called by instance. if (this instanceof Gadget) { // this only works if called non-statically msg += ", it costs $" + this.price + ‘!‘; } return msg;};// a normal method added to the prototypeGadget.prototype.setPrice = function (price) { this.price = price;};// a normal method added to the prototypeGadget.prototype.isShiny = function () { return Gadget.isShiny.call(this);};// Attempting to call an instance method statically won’t worktypeof Gadget.setPrice; // "undefined"
Testing a static method call:
Gadget.isShiny(); // "you bet"
Testing an instance, nonstatic call:
var a = new Gadget(‘499.99‘);a.isShiny(); // "you bet, it costs $499.99!"
Private Static Members
• Shared by all the objects created with the same constructor function
• Not accessible outside the constructor
// constructorvar Gadget = (function () { // static variable/property var counter = 0, NewGadget; // this will become the new constructor implementation NewGadget = function () { counter += 1; }; // a privileged method NewGadget.prototype.getLastId = function () { return counter; }; // overwrite the constructor return NewGadget;}()); // execute immediatelyvar iphone = new Gadget();iphone.getLastId(); // 1var ipod = new Gadget();ipod.getLastId(); // 2var ipad = new Gadget();ipad.getLastId(); // 3
References:
JavaScript Patterns - by Stoyan Stefanov (O`Reilly)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。