JavaScript中的静态成员
2024-10-19 02:21:44
静态:共享
一、公有静态成员(作为函数的属性即可):
var Gadget = function(price) {
this.price = price;
}
Gadget.isShiny = function(){
var msg = 'you bet';//公有静态
if(this instanceof Gadget){//实例调用时
msg += ', it costs ' + this.price + '!';
}
return msg;
}
Gadget.prototype.isShiny = function(){
return Gadget.isShiny.call(this)
} console.log(Gadget.isShiny());//you bet 此为静态调用
var a = new Gadget(23);
console.log(a.isShiny());//you bet, it costs 23! 此为实例调用
二、私有静态成员:
私有:构造函数外部不可访问
静态:所有实例共享
通过即时函数创建作用域存放
var Person;
(function(){
var id = 0;//私有
Person = function(){
id ++;
this.id = id;
}
Person.prototype.getId = function(){
console.log(this.id);
}
Person.prototype.getLastId = function(){
console.log(id);
} })(); var p1 = new Person();
p1.getLastId();//
p1.getId();// var p2 = new Person();
p2.getLastId();//
p2.getId()// var p3 = new Person();
p3.getLastId();//
p3.getId();// p1.getId();//
p2.getId();//
p3.getId();//
注:JavaScript设计 P108-111 略变
最新文章
- 如何通过一个类名找到它属于哪个jar包?
- Linux操作系统学习笔记
- asp控件Repeater运用
- HTTP中缓存相关
- GAC write failed when upgrade with InstallShield
- Normalize.css 介绍与源码解读
- STM32硬件IIC操作
- Zookeeper3.4.9分布式集群安装
- 用python画一朵玫瑰花
- RobotFrame连接MySql数据库
- 使用requirejs来管理angularJS依赖示例
- Django1-HTTP协议介绍
- (转载)js日期格式化转化
- Python 计算当真因子个数为偶数个时为幸运数,计算区间内幸运数之和
- Python 浅拷贝copy()与深拷贝copy.deepcopy()
- P2602 [ZJOI2010]数字计数
- [CC-BSTRLCP]Count Binary Strings
- [转]Angular2: Cannot read property 'name' of undefined
- 从 Firefox 35 版本开始,就无法兼容 PAC 式代理
- 20165214 实验一 Java开发环境的熟悉