日期:2014-05-16 浏览次数:20338 次
function range(from, to){ //编写的js代码 var r = inherit(range.methods); r.from = from; r.to = to; return r; } range.methods = { 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+ ")";} }; inherit = function(p){ //对象原型方法range.methods if(p==null) throw TypeError(); if(Object.create)Object.create(p); var t = typeof p; if(t != "function" && t!= "object") throw TypeError(); function f(){}; f.prototype = p; return new f(); };将上述js代码文件引入到页面中,在页面中编写的代码如下:
var r = range(1,3); //初始化函数 console.log(r.includes(2)); //true r.foreach(console.log); //1 2 3 console.log(r); //(1...3)
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 +")"; } };
var r = new Range(1,3); //通过构造函数创建对象 console.log(r.includes(2)); //true r.foreach(console.log);//123 console.log(r); //(1...3)
var F = function(){}; //一个函数对象 var p = F.prototype; //与F相关联的原型对象 var c = p.constructor; //与原型先关联的函数 console.log(c===F); //true 对于任意函数F.prototype.constructor==F
function defineClass(constructor,methods,statics){ //define.js if(methods) extend (constructor.prototype, methods); if(statics) extend (constructor, statics); return constructor; } function extend(o,p){ for(prop in p){ o[prop] = p[prop]; } return o; }
var SimpleRange = defineClass( //SimpleRange.js function(f,t) {this.f = f; this.t = t;}, { includes: function(x) {return this.f <= x && x <= this.t;}, toString: function() {return "("+this.f+"..."+this.t+")";} }, {upto:function(t) {return new SimpleRange(1,t);}});
var s = new SimpleRange(0,4); //在HTML中的执行方法(再次创建对象)[要引入上面两个js文件]
//方法1:var s = SimpleRange.upto(3);