0

There are codes which were implemented to show inheritance in Backbone.

GrandParent.js:

define([ "require", "jquery", "backbone"], function(require, $, Backbone) {

return Backbone.Model.extend({

    //for method, variable override
    name : "grandFa", //@ WILL BE Overrided
    familyName : "Song",
    age : 99,

    sayThis : function() { //@ WILL BE Overrided
        alert("GrandParent.this : "+this+" "+this.name);
    }

    });

 });

Parent.js:

define([ "require", "jquery", "backbone", "grandParent"], function(require, $, Backbone, GrandParent) {
    return GrandParent.extend({
        //for testing complicated this usage
        age : 50,
        //@Overrided
        name : "father",
        sayThis : function() {
            alert("Parent.this : "+this+" "+this.name);
        }
    });
});

Main.js:

require.config({
paths : {
        jquery : "libs/jquery-2.1.0",
        underscore : "libs/underscore-1.6.0",
        backbone : "libs/backbone-1.1.0",
        grandParent : "1-GrandParent",
        parent : "2-Parent"
    }
});

require(
["jquery","underscore", "backbone","grandParent","parent","child"], function($, _,Backbone, GrandParent, Parent, Child) {
    $(document).ready(function() {
        var grandParent = new GrandParent();
        var parent = new Parent();
        alert(parent.constructor.prototype.name); //=> parent
        alert(parent.__proto__.name); //=> parent   
    });
});

In this code parent.constructor.prototype.name and parent.__proto__.name looks totally same. Why did Backbone make 2 fields which works and looks totally same?

Is there any differences in constructor.prototype & __proto__?

Rohit416
  • 3,416
  • 3
  • 24
  • 41
Jinny Song
  • 125
  • 1
  • 10

1 Answers1

1

Is there any differences in constructor.prototype & __proto__ ?

__proto__ is actual object which is used to resolve the properties and methods on the lookup chain. JavaScript has the ability to achieve the inheritance which is done through prototypes. Every built in object can be extended using a prototype which is further used to create a new __proto__ e.g.

function Foo()
{
}

Foo.constructor.prototype == Foo.__proto__;  // returns true

But what happens here...

Foo.prototype == Foo.__proto__;  // returns false;

Must read on this topic here!.

So that is why you got same result when you alert. The thing is __proto__ is not meant to be expose/extend and it is never recommended. So you should not worry about them giving the same result. Backbone may have extended the prototypes of their custom functions/methods but it is JavaScript which created the __proto__ as a blueprint for them.

Community
  • 1
  • 1
Rohit416
  • 3,416
  • 3
  • 24
  • 41
  • 1
    `__proto__` is a deprecated accessor property that is inherited from `Object.prototype`. The actual property lookup chain goes through `Object.getPrototypeOf(…)` – Bergi Jun 27 '16 at 07:29