how to add a prototype to an object

Viewed 48

The following function produces the error 'scoreCounter is not defined' where it should be defined at that point as a prototype to Darts.

function Darts() {
    this.Score = 0
    this.x = 1
    this.y = 1
} 

Darts.prototype.scoreCounter = function(x,y) {
(unnecessary code for this quesiton)
}
const test = new Darts()


console.log(test.isPrototypeOf(scoreCounter))

how to fix this error(add the prototype correctly)

scoreCounter is expected to be part of test prototype as the output

2 Answers

You have only defined Darts.prototype.scoreCounter, not a variable with a name of scoreCounter; thus, the scoreCounter method is only visible on the prototype of Darts or on instances of the Darts function, i.e. new Darts().scoreCounter. To find whether or not a method has been defined on a function's prototype, you can use Object#hasOwnProperty or the in operator, depending on the situation.

function Darts() {
    this.Score = 0
    this.x = 1
    this.y = 1
} 

Darts.prototype.scoreCounter = function(x,y) {
 //(unnecessary code for this quesiton)
}
const test = new Darts()
console.log(test.hasOwnProperty("scoreCounter"));//false; it's a prototype property
console.log("scoreCounter" in test);
     //true; inherited property found on the prototype chain
console.log(Darts.prototype.hasOwnProperty("scoreCounter"));//true

In the console.log statement, you are testing 'scoreCounter', but 'scoreCounter' is not a global variable in your global workspace.

Try this:

console.log(Darts.prototype.isPrototypeOf(test))

^^^ We just need to check if the prototype/s in 'test' derives from 'Darts' higher up in its prototype chain. This will include any prototype inside of 'Darts' in the search.

Related