You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何测试添加到函数及函数原型上的方法?

测试函数自身方法与原型方法的工具和方法

嘿,我来帮你搞定函数自身方法和原型方法的测试问题,结合你的代码一步步拆解~

一、测试添加到函数自身的静态方法

你第一段的代码已经是个很好的实践啦,要验证这类方法,咱们可以从这几个角度入手:

1. 直接调用验证返回值

最直观的方式就是直接调用方法,看输出是否符合预期:

"use strict";
function aircraft() {
  return aircraft.myPlane();
}
aircraft.myPlane = () => 'XB-42';

// 直接调用静态方法
console.log(aircraft.myPlane()); // 输出 'XB-42'
console.log(aircraft()); // 你的原代码调用逻辑,同样输出 'XB-42'

2. 检查方法是否属于函数自身

用in操作符或者hasOwnProperty确认方法确实挂载在函数对象上,而非继承而来:

// 确认属性存在
console.log('myPlane' in aircraft); // true
// 确认是函数自身的专属属性
console.log(aircraft.hasOwnProperty('myPlane')); // true

3. 验证方法的类型

确保你挂载的确实是一个可执行的函数:

console.log(typeof aircraft.myPlane === 'function'); // true

二、测试添加到函数原型上的方法

你提到第二段原型方法的代码没写完,我先补全一个正确的示例,再讲测试方法,顺便帮你排查容易踩的坑:

先补全正确的原型方法代码

"use strict";
function aircraft(model) {
  // 构造函数里初始化实例专属属性
  this.model = model || 'Default';
}

// 给原型添加方法(注意别用箭头函数!箭头函数没有自己的this,会导致指向错误)
aircraft.prototype.getPlaneInfo = function() {
  return `Plane model: ${this.model}`;
};

测试原型方法的步骤

1. 通过实例调用验证返回值

原型方法是给构造函数的实例用的,必须先创建实例再调用:

const myPlane = new aircraft('XB-42');
console.log(myPlane.getPlaneInfo()); // 输出 'Plane model: XB-42'

2. 检查方法是否存在于原型链上

// 确认原型上存在该方法
console.log('getPlaneInfo' in aircraft.prototype); // true
console.log(aircraft.prototype.hasOwnProperty('getPlaneInfo')); // true

// 确认实例能继承到这个方法(实例自身没有,来自原型)
console.log('getPlaneInfo' in myPlane); // true
console.log(myPlane.hasOwnProperty('getPlaneInfo')); // false

3. 验证方法的继承关系

确认实例的方法确实指向原型上的方法:

console.log(myPlane.getPlaneInfo === aircraft.prototype.getPlaneInfo); // true

原型方法常见坑点排查

  • 用箭头函数作为原型方法:箭头函数没有自己的this,严格模式下会导致this指向undefined,调用时直接报错,原型方法一定要用普通函数。
  • 直接通过构造函数调用原型方法:如果直接写aircraft.prototype.getPlaneInfo(),此时this指向aircraft.prototype,拿不到实例的属性,必须通过实例调用。
  • 忘记用new创建实例:不用new调用构造函数时,严格模式下this是undefined,后续操作会直接报错。

内容的提问来源于stack exchange,提问作者DR01D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:22:36