Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototypal Inheritance. Whats wrong with this simple example?

    function a (){
        this.testing = 'testing';
    }

    function b (){

    }

    b.prototype = new a();



    console.log(b.testing);

The console shows undefined, rather than 'testing'. What am I doing wrong?

like image 933
Mark Brown Avatar asked Mar 28 '11 03:03

Mark Brown


People also ask

What is the point of prototypal inheritance?

Prototypical inheritance allows us to reuse the properties or methods from one JavaScript object to another through a reference pointer function.

How is prototypal inheritance different?

By now you must have realized the difference between classical inheritance and prototypal inheritance. Classical inheritance is limited to classes inheriting from other classes. However prototypal inheritance includes not only prototypes inheriting from other prototypes but also objects inheriting from prototypes.

What languages use prototypal inheritance?

Prototypal inheritance is a form of object-oriented code reuse. Javascript is one of the only [mainstream] object-oriented languages to use prototypal inheritance. Almost all other object-oriented languages are classical. In classical inheritance, the programmer writes a class, which defines an object.

How does JavaScript implement prototypal inheritance?

We can use obj. __proto__ to access it (a historical getter/setter, there are other ways, to be covered soon). The object referenced by [[Prototype]] is called a “prototype”. If we want to read a property of obj or call a method, and it doesn't exist, then JavaScript tries to find it in the prototype.


1 Answers

You haven't made an instance of 'b' yet.

var bInstance = new b();
console.log(bInstance.testing);

In other words, the properties of the prototype only appear on objects of type b, not on the b() constructor function itself.

like image 81
david Avatar answered Oct 27 '22 01:10

david