【问题标题】:Difference between Backbone.js 'constructor.prototype' and '__proto__'? [duplicate]Backbone.js 'constructor.prototype' 和 '__proto__' 的区别? [复制]
【发布时间】:2016-10-29 01:22:03
【问题描述】:

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__有什么区别吗?

【问题讨论】:

  • 其实这两个字段都不是Backbone做的。

标签: javascript backbone.js prototype-chain


【解决方案1】:

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 可能已经扩展了他们的自定义函数/方法的原型,但是 JavaScript 创建了 __proto__ 作为他们的蓝图。

【讨论】:

  • __proto__ 是一个已弃用的访问器属性,它继承自 Object.prototype。实际的属性查找链经过Object.getPrototypeOf(…)
猜你喜欢
  • 2015-09-29
  • 2010-10-13
  • 2023-03-21
  • 2021-01-26
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多