0
var P = {
    name: "James"
};

var j = Object.create(P);
console.log(j.name);
j.name = "James";
console.log(j.name);

P.prototype.test = "love";

console.log(P.test);

I have the code above. It gives me an error that I cannot set that I cannot set property 'test' of undefined. I thought every object has a prototype? Doesn't the P object have a prototype? and shouldn't any method declared on that prototype be available to j?

Also can someone explain to me what the Object.create() function does?

Chris Hansen
  • 7,813
  • 15
  • 81
  • 165
  • `P` does have a prototype from which it inherits: `Object.prototype` - in the same way that `j` inherits from `P`. `P` does not have a `.prototype` property though. – Bergi Oct 11 '15 at 18:39

1 Answers1

0

Ordinary objects such as P don't have .prototype properties. It's only functions that have that.

var o = {};
var f = function () {};

console.log(o.prototype); // nope
console.log(f.prototype); // there it is
Jeff M
  • 2,492
  • 3
  • 22
  • 38
  • 1
    *NOT* only functions have prototype! – Alex Shesterov Oct 11 '15 at 18:41
  • @alex-shesterov Can you be more specific? Show an example? – Jeff M Oct 11 '15 at 19:31
  • Well, if we are talking of properties named "prototype", then we can trivially define `var o = {prototype: {}};`. It won't be anything special, of course — just a regular property. If we are talking about the internal `[[prototype]]` property, then all regular objects have this. – Alex Shesterov Oct 11 '15 at 19:46
  • Both my answer and the OP's error was about properties named "prototype". And only functions *automatically* have that. – Jeff M Oct 11 '15 at 19:59