Вопрос

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();
Это было полезно?

Решение

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);

Другие советы

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(), ...

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);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top