Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Understanding Prototype chain

I created a simple class as follows:

var Class = function() {};
Class.prototype.testObj = {a:2, b:3};

Now if I do console.log(Class.testObj) I get undefined. But if i create instance of that Class as follows:

var instance = new Class();
console.log(instance.testObj)

I get expected output.

In my understanding, all variables are treated as Objects and have prototype property. When some key is not found in the object, prototype chain is traversed to look for the key-value pair. But in case of Class, it is not traversing the prototype chain.

What am I missing? What additional does new keyword do such that property is accessible?

like image 436
jsist Avatar asked Apr 09 '26 07:04

jsist


1 Answers

  1. You must be clear that Class() is your constructor, not an instance object. so Class.testObject will return undefined because Class doesn't have that property.

  2. You can think of a prototype as a recipe for an object. Almost every function has a prototype property that is used during the creation of new instances and that prototype is shared among all of the object instances

  3. A constructor is simply a function that is used with new to create an object

  4. When you do this var instance = new Class(); It means you are creating an instance object of Class, hence instance will inherit prototype properties of Class.

  5. Test:

    console.log(instance instanceof Class); // => true
    
    console.log(instance.constructor === Class); // => true
    
    console.log(Object.prototype.isPrototypeOf(Class)); // => true
    
    console.log(Class.prototype.isPrototypeOf(instance)); // => true
    
like image 164
babygau Avatar answered Apr 10 '26 22:04

babygau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!