0

What happens in memory when you add to an object's prototype in the constructor? Does it get it recreated every time you make a new object?

For example:

function Foo(){
  Foo.prototype.bar = function() {
    console.log("bar func called");
  }
}    
var x = new Foo();
x.bar();
var y = new Foo();
y.bar();

3 Answers 3

1

The "nature" of the code doesn't matter, it's executed every time you call it. This means that yes, every time you call new Foo() the function bar of the prototype is reassigned.

This also means that every Foo object out there get a new bar method, even those that already existed.

Sign up to request clarification or add additional context in comments.

1 Comment

And, you may want to add that this is a bad way to write code. The prototype should be assigned to once not repeatedly.
0

All code that you put in a function runs every time you call that function, even if said code assigns a property of a prototype.

Comments

0

Yes it does. The creation code will be executed each time you instantiate Foo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.