Reputation: 1365
Question: In the following code what can I use to see if I've added methods correctly or alternately what can I use to see how badly I screwed up?
In the following test code I add a method to a function and it works as expected.
"use strict";
function aircraft() {
return aircraft.myPlane();
}
aircraft.myPlane = () => 'XB-42';
console.log(aircraft());
In the next test code I add a method to the function's prototype and it also works as expected.
"use strict";
function aircraft() {
return aircraft.prototype.myPlane();
}
aircraft.prototype.myPlane = () => 'XB-42';
console.log(aircraft());
However in that last example I think I might have done something dumb but I'm not entirely sure. Did that add the .myplane()
function directly to the main Function prototype for all functions in the entire program? Is there a way for me to check and see what I've actually done so I can test and compare my results?
Upvotes: 1
Views: 26
Reputation: 370729
You need to distinguish between functions and classes (that use the function keyword). In the first example, you're simply adding properties to the function, not to an instantiation of a class (which is probably what you were trying to do).
In a function
constructor, you should reference that particular instantiation with this
, like the following:
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());
To assign to the prototype, do something like this:
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());
Upvotes: 1