标签:style blog http io os 使用 java ar strong
在支持“类”的面向对象语言中,静态成员指的是那些所有实例对象共有的类成员。静态成员实际是是“类”的成员,而非“对象”的成员。所以如果 MathUtils类中有个叫 max()的静态成员方法,那么调用这个方法的方式应该是这样的:MathUtils.max(3, 5)。
// constructor
var Gadget = function () {};
// a static method
Gadget.isShiny = function () {
return "you bet";
};
// a normal method added to the prototype
Gadget.prototype.setPrice = function (price) {
this.price = price;
};
// calling a static method Gadget.isShiny(); // "you bet" // creating an instance and calling a method var iphone = new Gadget(); iphone.setPrice(500);
typeof Gadget.setPrice; // "undefined" typeof iphone.isShiny; // "undefined"
Gadget.prototype.isShiny = Gadget.isShiny; iphone.isShiny(); // "you bet"
// constructor
var Gadget = function (price) {
this.price = price;
};
// a static method
Gadget.isShiny = function () {
// this always works
var msg = "you bet";
if (this instanceof Gadget) {
// this only works if called non-statically
msg += ", it costs $" + this.price + ‘!‘;
}
return msg;
};
// a normal method added to the prototype
Gadget.prototype.isShiny = function () {
return Gadget.isShiny.call(this);
};
Gadget.isShiny(); // "you bet"
而非静态的调用,也就是用对象来调用这个方法,结果则变成:
var a = new Gadget(‘499.99‘); a.isShiny(); // "you bet, it costs $499.99!"
var Gadget = (function () {
// static variable/property
var counter = 0;
// returning the new implementation
// of the constructor
return function () {
console.log(counter += 1);
};
}()); // execute immediately
var g1 = new Gadget(); // logs 1 var g2 = new Gadget(); // logs 2 var g3 = new Gadget(); // logs 3
// constructor
var 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 immediately
var iphone = new Gadget(); iphone.getLastId(); // 1 var ipod = new Gadget(); ipod.getLastId(); // 2 var ipad = new Gadget(); ipad.getLastId(); // 3
标签:style blog http io os 使用 java ar strong
原文地址:http://www.cnblogs.com/Bryran/p/3976149.html