When defining function on a prototype, is the function recreated on each new instance?

StackOverflow https://stackoverflow.com/questions/23157768

  •  05-07-2023
  •  | 
  •  

Domanda

I have the following code in javascript, and I am unclear on the underlying functionality of the following prototyping:

function TestClass()
{
}

var externalFunction = function() {
    console.log("hit the function defined internally");
};

Object.defineProperty(TestClass.prototype, "myFunction", {
    enumerable: false,
    writable: false,
    value: externalFunction
});

TestClass.prototype.myFunction2 = function() {
    console.log("hit the function defined on the prototype");
}

var tc = new TestClass();
var tc2 = new TestClass();

console.log(tc.myFunction === tc2.myFunction);
console.log(tc.myFunction2 === tc2.myFunction2);

Are either of myFunction or myFunction2 re-created whenever a new TestClass() is defined, or will the new TestClass() contain pointers to the original myFunction and myFunction2?

È stato utile?

Soluzione

Every object you create using the TestClass function as a constructor e.g.

var test1 = new TestClass();
var test2 = new TestClass();

will have the same prototype. What happens when you try to call the function :

test2.myFunction2();

is that the JS interpreter will look for myFunction2 on the object referenced by test2. It doesn't have a myFunction2 property, so it looks up the chain to see if the prototype of test2 has a property of type function called "myFunction2" - which it does, and so it calls it.

So to answer the question :

or will the new TestClass() contain pointers to the original myFunction and myFunction2?

The object you create with new TestClass() will contain a reference to an object (it's prototype) and that object contains the references to the two functions. Note that the reference between the new object and it's prototype is kind of secret, see :

here

This can be a source of extreme confusion since there are two things called "prototype" - there is a property of a the constructor function called "prototype" and there is the secret link (called e.g. proto in webkit). In code is seems a lot easier than it is to write it down :

var TestClass = function() {}
TestClass.prototype = {
   method: function() {}
};

var a = new TestClass();
console.log(a.__proto__ === TestClass.prototype); // true
console.log(a.method === TestClass.prototype.method); // true
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top