function IO() { this.foo = function() { alert("FOO"); } } IO.prototype.bar = function() { alert("BAR"); } var IO = new IO(); console.log(IO);
What is the difference between this
and prototype
ads?
function IO() { this.foo = function() { alert("FOO"); } } IO.prototype.bar = function() { alert("BAR"); } var IO = new IO(); console.log(IO);
What is the difference between this
and prototype
ads?
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
Source: https://ru.stackoverflow.com/questions/469398/
All Articles