理解“;静态“;方法

Understanding "static" methods in JavaScript

本文关键字:方法 静态 理解      更新时间:2023-09-26

我的困惑源于这个代码片段的最后一行:

function Animal(name) {
    Animal.count = Animal.count+1||1;// static variables, use function name "Animal"
    this.name = name; //instance variable, using "this"
}
Animal.showCount = function () {//static method
    alert(Animal.count)
}
Animal.prototype.showName=function(){//instance method
    alert(this.name);
}
var mouse = new Animal("Mickey");
var elephant = new Animal("Haddoop");
Animal.showCount();  // static method, count=2
mouse.showName();//instance method, alert "Mickey"
mouse.showCount();//Error!! mouse.showCount is not a function, which is different from  Java

问题:为什么mouse.showCount()不是一个函数?

JavaScript没有传统意义上的静态方法。您所要做的就是将一个函数指定为另一个函数(构造函数)的属性。记住,函数是JS中的对象。

因此,从构造函数创建的对象实例和构造函数本身之间没有直接关系。唯一的*关系是实例和构造函数的.prototype对象之间的关系。

如果要覆盖构造函数的.prototype,那么就不会有这种间接关系。因此,基本上,构造函数只是充当其.prototype和正在创建的新对象实例之间的临时"匹配器"。在那之后,构造函数就不再扮演任何角色。


*instanceof操作符看起来好像有一个连接,但它实际上只是将实例原型链中的对象与构造函数的.prototype对象进行比较,所以它仍然是一种间接关系,是一种可以打破的关系