2

I am new to JavaScript and currently reading the book "JavaScript: The Good Parts". I am trying to understand the following:

function create(proto) {
    var F = function() { };
    F.prototype = proto;
    return new F();
}
function create2(proto) {
    var o = { };
    o.prototype = proto;
    return o;
}
var o = { }, c1 = create(o), c2 = create2(o);
o.status = 'OK';
document.writeln(c1.status);
document.writeln(c2.status);

create(proto) is how this is done in the book. create2(proto) is how I thought it should work. Obviously, the example from the book is working while mine is not, so the output is:

OK
undefined

Now my question is: Why does create2(proto) not work like create(proto)?

2
  • there is because var o = { }; is an object literal and not a function Commented Dec 14, 2014 at 10:39
  • 1
    possible duplicate of How does JavaScript .prototype work? - F is a function while o is not. Commented Dec 14, 2014 at 10:55

2 Answers 2

4

In the create, you are creating a new object with the help of a constructor function (new F()). So, the prototype chain is established, between proto object and the object constructed with the constructor function.

In create2, you are creating an Object and creating a property on it with the name prototype. In this case, the prototype chain is not established.

That is why the object created by create2, couldn't go up the prototype chain to find status.

Note: In the second case, you can still do

document.writeln(c2.prototype.status);
Sign up to request clarification or add additional context in comments.

Comments

1

In create2 method if you need the standard prototype in not the standard "prototype". If you want this to work you need to use Object.setPrototypeOf(o, proto) The new created property "prototype" will be the satellite object that will have symbolic link to the parent object.

function create(proto) {
 var F = function() { };
 F.prototype = proto;
 return new F(); 
} 

function create2(proto) {
var o = { };
Object.setPrototypeOf(o, proto);
return o;
}
var o = { }, c1 = create(o), c2 = create2(o);
o.status = 'OK';
console.log(c1.status);
console.log(c2.status);

1 Comment

Thanks for the edit. FYI: This works fine in Chrome and Firefox, but not in Safari and also my IDE (IntelliJ IDEA Ultimate) doesn't recognize Object.setPrototypeOf(o, proto).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.