prototype和继承之间的关系有点奇怪。 一个对象是某个类型的实例,但是对象的原型却不等于其构造函数的原型
function Range(from,to) {
this.from = from;
this.to = to;
}
Range.prototype= {
includes:function(x){
return this.from <= x && x <= this.to;
},
foreach: function (f){
for(var x = Math.ceil(this.from);x<= this.to;x++) f(x);
},
toString: function() {return "(" + this.from + "..." + this.to + ")";}
};
function d(o){
console.debug(o);
}
var r3 = new Range(1,3);
d('r3.prototype == Range.prototype '+ (r3.prototype == Range.prototype));
d('r3 instance of Range:' + (r3 instanceof Range));
输出结果:
r3.prototype == Range.prototype false
r3 instance of Range:true
4.17更新
事实上 ,并不是“对象的原型却不等于其构造函数的原型”,
而是, r3.prototype 访问的并不是 r3的原型,只是一个一般的属性。
在firefox 里,要访问一个对象的属性的话,应该用它的 __proto__属性。
或者要判断一个对象的原型是不是某个类的话,可以用:
Range .isPrototypeOf(r3) 来判断
参考资料:
构造对象的几种方法的大白话版
http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_encapsulation.html
ECMAScript 继承机制实例
http://w3school.com.cn/js/pro_js_inheritance_in_action.asp
《Javascript 权威指南第6版》