Last active
December 15, 2015 04:39
-
-
Save jackfranklin/5203503 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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.
@mrappleton Ahh...my bad :) you are right.
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.
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
First one prints
5
for prototypical reasons. It first tries to findcount
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 makescount
key on the function object itself. Sox.count
simply gets the count of prototype. Hence,1
.