javascript 创建类

 使用构造函数来定义

/**
* 1.在javaScript中, 类的所有实例对像都是从同一个原型对像中继承属性. 因此对像是类的核心.
* 2.原型对象是类的唯一标识: * 当且仅当两个对象继承自同一个原型对象时, 它们才属于对一个类的实例. * 而构造函数则不能作为类的标识, 两个构造函数的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;

说明 : 每个JavaScript函数(ECMAScript 5 中的Function.bind()方法返回的函数除外) 都自动拥有一个prototype 属性.  这个属性的值是一个对像, 这个对像包含唯一一个不可

    枚举属性constructor.  constructor属性的值是一个函数对像. 如下实例:

var p = F.prototype;  // F相关联的原型
var c = p.constructor; // 原型相关联的函数
c === F      // --> true

var o = new F(); 
o.constructor = F; 

上边定义的 Range 类使用 一个新对象 重写预定义的 Range.prototype , 因此这个新定义的原型对像不含有 construnctor 属性.

可以通过以下方式 显示给原型添加一个构造函数:

Range.prototype = {
    constructor : Range,  // 显示设置构造函数的反向引用
     includes : function(x){return this.from <= x && x <=this.to;},
    toString : function(){return "("+this.from + "----"+this.to+")";}
}

//另一种常见的写法
Range.prototype.includes = function(x){....}

 

posted @ 2014-12-05 14:59  hewep  阅读(94)  评论(0编辑  收藏  举报