1 //超类和子类 继承的实现 2 3 function R(w, h) { 4 var date = new Date(); 5 this.width = w; 6 this.height = h; 7 this.createtime = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDay() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); 8 R.count++; 9 } 10 R.prototype.area = function () { 11 return this.width * this.height; 12 } 13 14 function P(x, y, w, h) { 15 R.call(this, w, h);//调用基类的构造函数,指定调用对象(如果不指定,它的调用对象,是它的定义域的相关作用域中的对象),用来初始化对象为其添加一些R初始化定义的属性,可尝试直接调用 16 //另外一种替代方法,使用P.prototype.superclass=R; 然后调用时 this.superclass(w,h) 也可以指定它的调用对象,因为superclass的定义时的作用域就是实例对象 17 this.x = x; 18 this.y = y; 19 } 20 P.prototype = new R();//设置原型对象为超类的一个实例对象,以后所有的P实例化对象,都会继承一个R实例对象的所有属性。 21 22 delete P.prototype.width; 23 delete P.prototype.height; 24 delete P.prototype.createtime; 25 //删除一些P实例化对象时,不需要继承的属性(一般),因为都已经在基类的构造函数定义了这些属性,成为了常规属性 26 27 P.prototype.constructor = P;//修改构造函数名 28 P.prototype.parea = function () { 29 return R.prototype.area.call(this);//调用被覆盖的基类函数 30 } 31 P.prototype.area = function () { 32 return "nothing"; 33 } 34 35 36 //添加新属性 37 P.prototype.contains = function (x, y) { 38 return (x > this.x && x < this.x + this.width && y > this.y && y < this.y + this.height); 39 } 40 var obj = new P(10, 20, 10, 10); 41 console.log(obj.contains(5, 5) + "\narea:" + obj.area() + "\nparea:" + obj.parea());
输出:
"false
area:nothing
parea:100"
//非继承的扩展
//从一个类的prototype得到到另外一个类的prototype
原文:http://www.cnblogs.com/tlxxm/p/4363045.html