Okay I'll give it a shot. I'm interviewing soon as well so it's good practice :)
function Person(){
this.a = function(){alert("a")};
}
Person.prototype.b = function(){alert("b")};
Person.c=function(){alert("c")};
var test = new Person();
test.a(); // works
test.b(); // works
test.prototype.b(); //error
Sounds like you got this, but test
is an object, not a constructor. It has no prototype key on it.
Person.prototype.a(); // error (why?)
Person.prototype.b(); //works (why?)
Here's where things get fun. Look at the Person()
function; all it really does reference the parameters passed to it and returns a new object. Doesn't seem more complicated than that. However, this is where JavaScript's crazy prototypical inheritance comes into play.
Say you wrote a higher-level prototype method on String
, like String.prototype.capitalize = function()...
, and the method capitalized the string. Every new string you created would have the capitalize()
method on it, but it's not like the string is an object with that method key on it.
It's the same here with what Person.prototype.a()
and Person.prototype.b()
is doing. Running an object through the Person()
function creates an object with those keys. Since the Person()
constructor only returns an object with a key of a, this is what test
looks like so far:
console.log(test); // {a: [Function]}
But why does test.b()
work? It's because any object created by a constructor inherits all the properties on that constructors .prototype
. Adding something to the prototype doesn't change the keys added to the constructed object but instead gives its constructed objects access to it. Calling a method on something first looks at it's keys, then it's constructor's hidden [[prototype]] value, then it's parent, and so on. You can see this in console.log
s in Chrome.
Person();
Person.a(); /* error (Person() call should have set this.a
on the Person object just like the c method,
why doesn’t it work?) */
Person.b();//error (why?)
Your mistake here is saying that Person()
is an object. It's not; it's a function. The this
reference in the constructor refers to the object being passed to it; that means the variable it's being set to. Since we are just calling Person()
and not setting the result to anything, this
is undefined and the result of Person()
is undefined as there's nothing to return. A function can't have keys or methods.
Hope I could help. This was good practice for me too!