Search code examples
javascriptprototypeprototype-chain

Javascript Prototype chaining change the target


I am a student studying programming.

I have a question.

    function a () {

    }

    a.prototype.prtSomething = function(arg) { console.log(arg); }

    function b () {

    }

    var myObj = new b();

If I want to use the method of a in myObj, we use this code.

b.prototype = Object.create(a.prototype);
b.prototype.constructor = b;

That means changing the target of scope chaining. But why don't we use this code?

b.prototype.__proto__ = a.prototype;

I think there must be a reason to creating and using a new object. but I don't know. Please teach me. Thank you.


Solution

  • For at least one good reason: the __proto__ feature is deprecated, so you shouldn't use it for future compatibility.

    I recommend reading MDN page on the topic, and also linked pages on inheritance if you are learning.

    USEFUL ADDITIONAL NOTE: using b.prototype = Object.create(a.prototype); is a way to simulate Class inheritance in a prototype way (b inherits from a) without the "parent" (a) constructor to be called. If you would rather prefer to simulate inheritance with "parent" constructor being called, you can use b.prototype = new a();

    Of course it's a emulation of class behavior, it differs in details because prototypes are not classes, for example you can dynamically add functions to a's prototype after an instance of b has been created, and the new function will be available for the instance because it works by reference. In a similar way the second example doesn't execute a's constructor for every further instance, but only once when you assign it to b's prototype.

    Actually I find prototypes really powerful when you get to know them, allows many combinations.

    function a () {
        console.log('a constructor');
    }
    
    a.prototype.prtSomething = function(arg) { console.log(arg); }
    
    function b () {
        console.log('b constructor');
    }
    
    b.prototype = Object.create(a.prototype);
    b.prototype.constructor = b;
    
    var myObj = new b();

    function a () {
        console.log('a constructor');
    }
    
    a.prototype.prtSomething = function(arg) { console.log(arg); }
    
    function b () {
        console.log('b constructor');
    }
    
    b.prototype = new a();
    b.prototype.constructor = b;
    
    var myObj = new b();