js 静态方法与实例方法

[size=medium][color=red][b]静态方法是指不需要声明类的实例就可以使用的方法[/b][/color][/size]

[size=medium][color=blue][b]实例方法是指必须要先使用"new"关键字声明一个类的实例, 然后才可以通过此实例访问的方法[/b][/color][/size]

//声明一个类
function staticClass() { };
//创建一个静态方法
staticClass.staticMethod = function() { alert("static method") };
//创建一个实例方法
staticClass.prototype.instanceMethod = function() { "instance method" };


上面首先声明了一个类staticClass, 接着为其添加了一个静态方法staticMethod 和一个动态方法instanceMethod。[color=red][b]区别就在于添加动态方法要使用prototype原型属性。[/b][/color]

对于静态方法可以直接调用 staticClass.staticMethod();
[color=blue][b]但是动态方法不能直接调用 staticClass.instanceMethod(); //语句错误, 无法运行。[/b][/color]

需要首先实例化后才能调用 var instance = new staticClass(); //首先实例化
instance.instanceMethod(); //在实例上可以调用实例方法


//模拟静态
var Animal = function(name){
this.name = name;
Animal.instanceCounter ++;
};
Animal.instanceCounter = 0;

Animal.prototype.sayHellow = function(){
console.log('this.name');
}

var animal = new Animal('name');
var animal2 = new Animal('name2');
console.log(Animal.instanceCounter);//2
console.log(animal.instanceCounter);//undefined
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值