>问题:在下面的代码中,我可以使用什么来查看我是否正确添加了方法,或者我可以使用什么来查看我搞砸了多少?
在下面的测试代码中,我向函数添加了一个方法,它按预期工作。
"use strict";
function aircraft() {
return aircraft.myPlane();
}
aircraft.myPlane = () => 'XB-42';
console.log(aircraft());
在下一个测试代码中,我将一个方法添加到函数的原型中,该方法也可以按预期工作。
"use strict";
function aircraft() {
return aircraft.prototype.myPlane();
}
aircraft.prototype.myPlane = () => 'XB-42';
console.log(aircraft());
然而,在最后一个例子中,我想我可能做了一些愚蠢的事情,但我并不完全确定。 这是否将.myplane()
函数直接添加到整个程序中所有函数的主函数原型中? 有没有办法让我检查并查看我实际做了什么,以便我可以测试和比较我的结果?
您需要区分函数和类(使用函数关键字(。在第一个示例中,您只是将属性添加到函数,而不是添加到类的实例化(这可能是您尝试执行的操作(。
在 function
构造函数中,您应该使用 this
引用该特定实例,如下所示:
function Aircraft() {
// function constructor (doesn't do anything useful in either example)
}
const myAircraft = new Aircraft();
// assigns to this instantiation only:
myAircraft.myPlane = () => 'XB-42';
console.log(myAircraft.myPlane());
要分配给原型,请执行以下操作:
function Aircraft() {
// function constructor (doesn't do anything useful in either example)
}
// applies to all Aircraft:
Aircraft.prototype.myPlane = () => 'XB-42';
const myAircraft = new Aircraft();
console.log(myAircraft.myPlane());