Skip to content

Instantly share code, notes, and snippets.

@jackfranklin
Last active December 15, 2015 04:39
Show Gist options
  • Save jackfranklin/5203503 to your computer and use it in GitHub Desktop.
Save jackfranklin/5203503 to your computer and use it in GitHub Desktop.
var Basket = function() {
this.count = 5;
};
Basket.prototype.count = 1;
var x = new Basket();
console.log(x.count); // 1 or 5? (and why?)
// and
var Basket = function() {};
Basket.prototype.count = 1;
var x = new Basket();
x.count = 5;
console.log(x.count); // 1 or 5? (and why?)
@chinchang
Copy link

First one prints 5 for prototypical reasons. It first tries to find count on the object and then on prototype. As it finds the key on the object itself, 5 is returned.

In second case, Basket.count doesn't set it on the object or prototype. Rather it makes count key on the function object itself. So x.count simply gets the count of prototype. Hence, 1.

@appleton
Copy link

@chinchang The second case would also log 5 for the same reason as the first case. x is the object returned by the constructor function, not a reference to the function so it would try to access x.count and find it before looking for x.__proto__.count

The two examples are essentially equivalent.

@chinchang
Copy link

@mrappleton Ahh...my bad :) you are right.

@jackfranklin
Copy link
Author

Sorry for the confusion @chinchang @mrappleton - I made a mistake in my example facepalm. The second example was wrong - as you point out setting Basket.count doesn't really do much of value. Updated it now.

@chinchang
Copy link

haha. I was wondering how come I wrote the second O/P wrong :P

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment