js 类创建的 三种方式
时间:2014-12-05 15:42:16
收藏:0
阅读:198
第一种方式: 简单的 JavaScript 类(使用工厂方法)
1. 首先 通过原型继承创建一个对象
第二种方式: 使用构造函数来定义
/**原型对象是类的唯一标识: * 当且仅当两个对象继承自同一个原型对象时, 它们才属于对一个类的实例. * 而构造函数则不能作为类的标识, 两个构造函数的prototype属性可能指向同一个原型对象, * 那么这两个构造函数创建的实例就属于同一个类. * */
function Range(from, to){
this.from = from;
this.to = from;
};
Range.prototype = {
includes : function(x){return this.from <= x && x <=this.to;},
toString : function(){return "("+this.from + "----"+this.to+")";}
};
var r = range(1,3);
r.includes(2);
console(r);
/** * 实际上 instanceof 并不会检车 r 是否是 有 Range() 构造函数初始化而来的, * 而会检查r 是否继承自 Range.prototype */
r instanceof Range //如果r继承自 Range.prototype, 则返回true;
评论(0)