js 静态方法与实例方法

来源:互联网 发布:杨氏弹性模量数据ed 编辑:程序博客网 时间:2024/06/04 19:38
静态方法是指不需要声明类的实例就可以使用的方法

实例方法是指必须要先使用"new"关键字声明一个类的实例, 然后才可以通过此实例访问的方法
//声明一个类function staticClass() { }; //创建一个静态方法staticClass.staticMethod = function() { alert("static method") }; //创建一个实例方法staticClass.prototype.instanceMethod = function() { "instance method" };


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

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

需要首先实例化后才能调用   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);//2console.log(animal.instanceCounter);//undefined



0 0
原创粉丝点击