On Wed, Jun 8, 2011 at 11:29 AM, Raincole Lai <[email protected]> wrote:
> I read an article which explains what prototype chain is.
>
> It says that if I try to access an object's property but it doesn't have it,
> javascript engine will try it's .constructor.propotype. If it doesn't have
> it either then try .construtor.propotype.constructor.propotype. Untill it
> find the built-in Object().
>
> But I test this:
>
> function a() {}
> b = new a();
> c = b.constructor.prototype
>
> I get an empty a object.
>
> d = c.constructor.prototype
>
> I get an empty a object.
Try the following instead:
function F(){};
F.prototype = {foo: 'Alice', bar: 'Bob'};
var a = new F();
var b = new F();
If you inspect a or b in firebug (or equivalent) you will see object
{foo: 'Alice', bar: 'Bob'};
Now try: a.foo = 'Carol';
If you inspect F.prototype or b in firebug you will still see {foo:
'Alice', bar: 'Bob'}.
Now try: F.prototype.foo = 'Dan';
This time b.foo == 'Dan' while a.foo == 'Carol' still.
This is what the explanation you were confused by is referring to.
The 'new' keyword is passing an empty object[1] to variables a and b,
plus a hidden reference to F.prototype. When you do a call to a.foo,
the Javascript engine checks 'a' for property foo, sees that it is
undefined, but because 'a' has been given F.prototype as a default, it
tries there next. This time it finds the value 'Alice', which it
returns.
When you set a.foo = 'Carol', you are setting the property of a
itself. This time, when you call a.foo, the engine goes to a, sees
that foo has been defined, and returns 'Carol' straight away, without
checking the prototype.
This is a powerful form of inheritance, though it is clumsily
implemented in Javascript. Douglas Crockford's Object.create() method
wraps the above in a more elegant function. An example of
instantiating variable 'a' with Object.create() would be:
var a = Object.create({foo: 'Alice', bar: 'Bob'});
Regards,
David M
[1] it actually passes the function F's special 'this' object, which
in the above example is empty, but I shall leave the explanation of
this, if you wish it, to a separate email.
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]