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)?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Christian Schlichtherle
  • 3,125
  • 1
  • 23
  • 47
  • there is because var o = { }; is an object literal and not a function – ale Dec 14 '14 at 10:39
  • 1
    possible duplicate of [How does JavaScript .prototype work?](http://stackoverflow.com/q/572897/1048572) - `F` is a function while `o` is not. – Bergi Dec 14 '14 at 10:55

2 Answers2

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);
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
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);
Kiba
  • 10,155
  • 6
  • 27
  • 31
  • 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)`. – Christian Schlichtherle Dec 14 '14 at 11:24