在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.name
,parent.__proto__.name
看起来完全一样。为什么Backbone制作了两个有效且外观完全相同的字段?
constructor.prototype
&中有什么区别__proto__
吗?
constructor.prototype
&中有什么区别__proto__
吗?
__proto__
是实际对象,用于解析查找链上的属性和方法。JavaScript具有实现通过原型完成的继承的能力。每一个建于物体可以使用扩展prototype
其还用于创建一个新的__proto__
如
function Foo()
{
}
Foo.constructor.prototype == Foo.__proto__; // returns true
但是这里发生了什么...
Foo.prototype == Foo.__proto__; // returns false;
这就是为什么您发出警报时得到相同结果的原因。该事物__proto__
并不意味着要公开/扩展,并且从不建议这样做。因此,您不必担心它们会产生相同的结果。Backbone可能扩展了其自定义函数/方法的原型,但是JavaScript为其创建__proto__
了蓝图。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句