JavaScript 超类与子类 继承

时间:2023-03-09 04:39:24
JavaScript 超类与子类 继承
 //超类和子类   继承的实现 

 function R(w, h) {
var date = new Date();
this.width = w;
this.height = h;
this.createtime = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDay() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
R.count++;
}
R.prototype.area = function () {
return this.width * this.height;
} function P(x, y, w, h) {
R.call(this, w, h);//调用基类的构造函数,指定调用对象(如果不指定,它的调用对象,是它的定义域的相关作用域中的对象),用来初始化对象为其添加一些R初始化定义的属性,可尝试直接调用
//另外一种替代方法,使用P.prototype.superclass=R; 然后调用时 this.superclass(w,h) 也可以指定它的调用对象,因为superclass的定义时的作用域就是实例对象
this.x = x;
this.y = y;
}
P.prototype = new R();//设置原型对象为超类的一个实例对象,以后所有的P实例化对象,都会继承一个R实例对象的所有属性。 delete P.prototype.width;
delete P.prototype.height;
delete P.prototype.createtime;
//删除一些P实例化对象时,不需要继承的属性(一般),因为都已经在基类的构造函数定义了这些属性,成为了常规属性 P.prototype.constructor = P;//修改构造函数名
P.prototype.parea = function () {
return R.prototype.area.call(this);//调用被覆盖的基类函数
}
P.prototype.area = function () {
return "nothing";
} //添加新属性
P.prototype.contains = function (x, y) {
return (x > this.x && x < this.x + this.width && y > this.y && y < this.y + this.height);
}
var obj = new P(10, 20, 10, 10);
console.log(obj.contains(5, 5) + "\narea:" + obj.area() + "\nparea:" + obj.parea());

输出:
"false
area:nothing
parea:100"

//非继承的扩展
//从一个类的prototype得到到另外一个类的prototype