Reputation: 31
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();
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;
Upvotes: 0
Views: 38
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();
Upvotes: 1
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