javascript中借用别的类的方法
借用别的类的方法
/**
* Created by Administrator on 2015/12/23.
*/
//====================借用方法===============================
function borrowMethods(borrowFrom,addTo){
var from = borrowFrom.prototype;
var to = addTo.prototype;
for(m in from){
if(typeof from[m]!="function"){
continue;
}
to[m] = from[m];
}
}
// 带有通用的toString()方法的类
function GenericToString(){}
GenericToString.prototype.toString = function(){
var props = [];
for(var name in this){
if(!this.hasOwnProperty(name)) continue;
var value = this[name];
var s = name+":";
switch (typeof value){
case "function": s+="function";
break;
case "object":
if(value instanceof Array) s+="array";
else s+=value.toString();
break;
default :
s += String(value);
break;
}
props.push(s);
}
var str = "";
if(props.length>0){
str+="[";
for(i=0;i<props.length;i++){
str += props[i];
if(i<props.length-1){
str+=",";
}
}
str +="]";
}
return str;
}
// 带有通用的equals()方法的类
function GenericEquals(){}
GenericEquals.prototype.equals = function(that){
if(this == that){
return true;
}
var propsInThat = 0;
for(var name in that){
propsInThat++;
//如果属性值不相同,返回false
if(this[name]!==that[name]){
return false;
}
}
var propsInThis =0;
for(name in this) propsInThis ++;
//判断属性个数是否相等
if(propsInThat != propsInThis){
return false;
}
return true;
}
//声明Rectangle类
function Rectangle(w, h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function () {
return this.width * this.height;
}
borrowMethods(GenericToString,Rectangle);
borrowMethods(GenericEquals,Rectangle);
var rectangle = new Rectangle(50,100);
console.log(rectangle.toString());
console.log(rectangle instanceof Object);
console.log(rectangle instanceof Rectangle);
console.log(rectangle.constructor == Object);
console.log(rectangle.constructor == Rectangle);
d