javascript - Backbone.js 'constructor.prototype' 和 '__proto__' 之间的区别?

标签 javascript backbone.js prototype-chain

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

在此代码中parent.constructor.prototype.nameparent.__proto__.name看起来完全一样。为什么 Backbone 制作了 2 个工作原理和外观完全相同的字段?

constructor.prototype有什么不同吗? & __proto__

最佳答案

Is there any differences in constructor.prototype & __proto__ ?

__proto__是用于解析查找链上的属性和方法的实际对象。 JavaScript 能够通过原型(prototype)来实现继承。每个内置对象都可以使用 prototype 进行扩展进一步用于创建新的 __proto__例如

function Foo()
{
}

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

但是这里发生了什么......

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

Must read on this topic here! .

这就是为什么当您发出警报时会得到相同的结果。事情是__proto__并不意味着暴露/扩展,它是 never recommended 。所以你不应该担心他们会给出相同的结果。 Backbone 可能扩展了其自定义函数/方法的原型(prototype),但创建 __proto__ 的是 JavaScript。作为他们的蓝图。

关于javascript - Backbone.js 'constructor.prototype' 和 '__proto__' 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38047003/

相关文章:

json - Backbone.js中使用hunchentoot解析model.save()发送的post请求

JavaScript应用架构: Referencing Object Properties

javascript - Marionette 带路由的深层嵌套区域

javascript - 组合 javascript 原型(prototype)样式

javascript - 我应该如何在 MYSQL 中存储列表的列表

javascript - 手动编辑 "Thumbnail grid with expanding preview"的html/更改.js?

javascript - 无法读取未定义的属性 'force'(简单 D3 网络图)

javascript - 滚动经过每个部分时更改 SVG 的颜色

javascript - Function 和 Function.prototype 的区别

JavaScript 遍历对象属性和原型(prototype)链