1

The below code is saying object has no method hehe

var A = function () {
                this.hehe = function () { };
            };
var B = function () {};
B.prototype = Object.create(A.prototype, {
                constructor: {
                    value: B,
                    enumerable: false,
                    writable: true,
                    configurable: true
                }
            });
var _b = new B();
    _b.hehe();
Sanjeev
  • 1,838
  • 1
  • 16
  • 28
williamsandonz
  • 15,864
  • 23
  • 100
  • 186
  • http://blog.slaks.net/2013-09-03/traditional-inheritance-in-javascript/ – SLaks Dec 06 '13 at 03:06
  • If you want to know more about constructor functions and prototype maybe this answer will help you: http://stackoverflow.com/a/16063711/1641941 – HMR Dec 06 '13 at 03:48

3 Answers3

1

If you want B to have access to that function you need to define it in the prototype of A.

A.protototype.hehe = function(){
 //do something
};

Your call to the parents constructor is also missing in b.

With this.hehe every instance of A is getting it's own hehe function, thus not being in the prototype.

Also a nicer implentation of prototypal inhertiance is as follows - Well that is a matter of opinion I know.

function __extends(child,parent){ //Global function for inheriting from objects

    function Temp(){this.constructor = child;} //Create a temporary ctor
    Temp.prototype = parent.prototype; 
    child.prototype = new Temp(); //Set the child to an object with the child's ctor    with the parents prototype
}

var B = (function(_parent){
__extends(B,A);

function B(){

 _parent.call(this);
 }

})(A);
Lee Brindley
  • 6,242
  • 5
  • 41
  • 62
1

You should be passing an instance of A as the prototype, not A's prototype.

i.e. you should call your create call should look like Object.create(new A(), ...

Thayne
  • 6,619
  • 2
  • 42
  • 67
  • 1
    No, you should pass the object which should be the prototype of the newly-created object. – mechanicalfish Dec 06 '13 at 03:08
  • Sorry, now I know what you meant. – mechanicalfish Dec 06 '13 at 03:10
  • 1
    If hehe can be set directly on the prototype than @Fendorio's answer is great. But if hehe needs to be inside of A (for example if it is a closure) then either a new A needs to be created, or A() needs to be called inside of B on B's this (as in SLaks answer). In the latter case a new hehe will be defined for each B, which may not be desirable. Although my answer may be the best in all situations, it may be apropriate in some situations. – Thayne Dec 06 '13 at 03:38
0

hehe() is not a member of A.prototype; it's a property of each A instance assigned in its constructor.

Since you never call the A constructor, _b doesn't have it.

You need to call your base constructor in the derived constructor:

A.call(this);
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964