1 //类 构造函数 原型对象 this代表调用对象 2 function R(w, h) { 3 var date = new Date(); 4 this.width = w; 5 this.height = h; 6 this.createtime = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDay() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); 7 8 } 9 R.prototype.area = function () { 10 return this.width * this.height; 11 } 12 var o = new R(10, 20); 13 console.log(o.createtime + ":" + o.area());
输出:"2015-2-2 0:8:11:200"
1 //类 构造函数 原型对象 this代表调用对象 2 function R(w, h) { 3 var date = new Date(); 4 this.width = w; 5 this.height = h; 6 this.createtime = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDay() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); 7 R.count++; 8 } 9 R.prototype.area = function () { 10 return this.width * this.height; 11 } 12 //以上创建的都是实例属性和实例方法,以下为类属性和类方法 13 R.count = 0; 14 R.getCount = function () { 15 return R.count; 16 } 17 18 var o = new R(10, 20); 19 console.log("createtime:" + o.createtime + "\narea:" + o.area() + "\nR.count=" + R.getCount()); 20 var o2 = new R(20, 30); 21 console.log("createtime:" + o2.createtime + "\narea:" + o2.area() + "\nR.count=" + R.getCount());
输出:
createtime:2015-2-2 0:9:14
area:200
R.count=1
createtime:2015-2-2 0:9:14
area:600
R.count=2
1 //私有属性(只能通过专门的方法才能读取和写入),使用了闭包原理,因为里面定义的函数被外部的全局对象引用了, 2 //外部函数的调用对象不会被释放,w 和 h值一直维持最近一次的值,并且直到外部的引用消失,才会被释放内存 3 function R(w, h) { 4 this.getWidth = function () { 5 return w; 6 } 7 this.getHeight = function () { 8 return h; 9 } 10 this.setWidth = function (width) { 11 w = width; 12 } 13 this.setHeight = function (height) { 14 h = height; 15 } 16 } 17 var o = new R(10, 20); 18 alert(o.getWidth() * o.getHeight()); 19 o.setWidth(100); 20 o.setHeight(200); 21 alert(o.getWidth() * o.getHeight());
输出:
200
20000
原文:http://www.cnblogs.com/tlxxm/p/4362043.html