0

I'm studying javascript prototype.

CASE 01 - works!

var A = function() {}
A.prototype.hello = function() {
  console.log('hello');
}

var B = function() {}
B.prototype = new A();

var C = function (){}
C.prototype = new B();

var c = new C();
c.hello();

CASE 02 - doesn't work!

var A = {
  hello : function() {
    console.log('hello');
  }
}
var B = {}
B.prototype = A;
var C = {}
C.prototype = B;
C.hello();

I think I didn't understand the concept of prototype and constructor or how the objects inherit each other. Can anybody explain why CASE 02 doesn't work?

Lemile
  • 45
  • 3
  • I'd argue that it [doesn't actually work](https://stackoverflow.com/questions/12592913/what-is-the-reason-to-use-the-new-keyword-here) – Bergi Mar 26 '19 at 07:30

3 Answers3

0

B.prototype is just going to be a key on B object since B.prototype = A is going to create a key name prototype on B. Same happens with C , it will create a nested key of prototype

var A = {
  hello: function() {
    console.log('hello');
  }
}
var B = {}
B.prototype = A;
console.log(B)
var C = {}
C.prototype = B;
console.log(C)
C.prototype.prototype.hello();
brk
  • 48,835
  • 10
  • 56
  • 78
0

I can not really explain, but for me it's just a question of syntax:

var A = {
  hello : function() {
    console.log('hello');
  }
}

var X = Object.create(A);
X.hello();
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
0

I think the point to note is that prototype is a property of function AND not an object. Case 2 does NOT work mainly because of this reason.

trk
  • 2,106
  • 14
  • 20