function IO() { this.foo = function() { alert("FOO"); } } IO.prototype.bar = function() { alert("BAR"); } var IO = new IO(); console.log(IO); 

console.log

What is the difference between this and prototype ads?

  • adding to the current object - respectively, each instance will have its own copy of the field / function, or adding to the prototype and all objects will have access to one field / function instance - Grundy
  • didn’t quite understand what it means to inherit - Grundy

2 answers 2

In this case, the function will be created every time an object is created, and can use variables declared inside the constructor in the closure.

 function IO() { var _private = 10; this.foo = function() { _private = 15;//OK alert("FOO"); } } 

In this case, the function is created once and does not have access to the variables locally declared in the constructor.

 IO.prototype.bar = function() { var some = _private + 15;// Uncaught ReferenceError: _private is not defined alert("BAR"); } 

    As Grundy said in the comments, this

     this.foo = function() { /*...*/ } 

    creates a copy of the function for each instance, and this

     IO.prototype.bar = function() { /*...*/ } 

    creates one function for all instances. You can see this difference in this way:

     var a = new IO(), b = new IO(); console.log(a.foo === b.foo); // false console.log(a.bar === b.bar); // true 
    • :-D I then managed to roll back the answer - Grundy
    • @Grundy I noticed, I also voted) - Peter Olson
    • By the way, thanks for editing, I didn’t remember exactly how the error might look like when accessing an undeclared variable - Grundy