kushal bhandari
kushal bhandari

Reputation: 31

Javascript inheritence without prototype

Please refer - http://jsfiddle.net/sf4oaxun/

function a() {
    this.say = function () {
        alert("hello");
    };
}

a.prototype.what = function () {
    alert("234234");
};

function b() {}

//b.prototype = Object.create(a);
//b.prototype = a;

var b1 = new b();

b1.say();
  1. The 2 commented lines, are they different?
  2. Why does say not get invoked, and errors out when using either of the commented lines(please uncomment it)

    b.prototype = Object.create(a);
    b.prototype = a;
    
  3. Quick question added - If 'b' is inheriting from 'a' using b.prototype = Object.create(a.prototype), then would instances of b not be able to call any method of a which is not defined on a's prototype? Please refer - jsfiddle.net/sf4oaxun/3

Upvotes: 0

Views: 38

Answers (2)

mohamedrias
mohamedrias

Reputation: 18566

say is only available within the function a's constructor. It will not be inherited.

so that's the reason why b1.say() was not available.

Another thing, both the statements are wrong.

It should be either

b.prototype = Object.create(a.prototype)

so that what property will be inherited by b.

Another way of doing is

b.prototype = a.prototype

But in this case, any changes to b.prototype will affect a.prototype

In case if you want to inherit the constructor properties as well, then

b.prototype = new a();

DEMO

Upvotes: 1

TomFuertes
TomFuertes

Reputation: 7270

When you use Object.create the prototype is curried over, but your constructor is never run. This the code inside the original A "class" isn't actially executing. To get b1 to have both say and what, you would do

b.prototype = new a();

Upvotes: 0

Related Questions