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 制作了 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/