类方法(static)定义在类自身,原型方法定义在类的prototype上;验证原型方法需满足:实例无自有属性但可访问、in为true而hasownproperty为false、prototype上存在该函数、prototype.isprototypeof实例为true。

类方法并不定义在原型对象上,这是常见的误解。真正定义在原型上的,是类中声明的方法(即 method() { } 这种语法),而“类方法”通常指直接挂在类(构造函数)本身上的静态方法(static method() { }),它既不在实例上,也不在原型链上。
怎么验证一个方法是否在原型上?
关键看它能否被所有实例共享、是否可通过 hasOwnProperty 和 isPrototypeOf 判断归属:
-
用
hasOwnProperty检查实例:如果instance.hasOwnProperty('methodName') === false,但instance.methodName可访问,说明该方法来自原型 -
用
in运算符对比:若'methodName' in instance为true,但instance.hasOwnProperty('methodName')为false,就确认它是继承自原型的 -
查原型对象本身:直接访问
MyClass.prototype.methodName,能取到函数体即说明定义在原型上 -
用
isPrototypeOf:例如MyClass.prototype.isPrototypeOf(instance)返回true,且该方法存在,可佐证其原型归属
典型反例:类字段 vs 类方法
下面代码会让人误以为“同名 method 是类方法”,实则混淆了两类机制:
class Parent {
method = 'data'; // ← 实例属性,写入 this 上
}
class Child extends Parent {
method() { } // ← 确实定义在 Child.prototype 上
}
const c = new Child();
console.log(c.hasOwnProperty('method')); // true —— 来自 Parent 字段,遮蔽了原型方法
此时 c.method 是字符串,不是函数;Child.prototype.method 虽存在,但被实例自有属性屏蔽,无法通过 c.method() 调用。
真正的原型方法验证示例
干净定义一个仅含原型方法的类:
class Animal {
speak() {
return 'sound';
}
}
const a = new Animal();
console.log(a.hasOwnProperty('speak')); // false
console.log('speak' in a); // true
console.log(Animal.prototype.speak); // function speak() { ... }
console.log(Animal.prototype.isPrototypeOf(a)); // true
这组结果共同证明:speak 是定义在 Animal.prototype 上的原型方法。
补充:静态方法(static)在哪?
静态方法属于类自身,不参与实例或原型链:
-
Animal.staticMethod存在,可直接调用 -
a.staticMethod是undefined -
Animal.prototype.staticMethod是undefined -
Animal.hasOwnProperty('staticMethod')为true
它和原型方法是两个独立体系,不要混为一谈。











