About Inherence

1、封装
写道
function extend(parent,child){
var F = function(){};
F.prototype = parent.prototype;
child.prototype = new F();
child.prototype.constructor = child;
child.uber = parent.prototype;
}

  
  

2、复制属性

写道
function extend2(parent,child){
var p = parent.prototype;
var c = child.prototype;
for(var i in p){
c[i] = p[i];
}
c.uber = p;
}
 

 

结果:

写道
function shape(){};
shape.prototype.name = 'shape';
shape.prototype.toString = function(){return this.name;}

function Triangle(){}
extend(shape,Triangle);
var s = new Triangle();
s.toString();// "shape"
s.name;// "shape"

extend2(shape,Triangle);
var t = new Triangle();
t.name;//"shape"
 
3、多继承的实现
function multi() {
var n = {}, stuff, j = 0, len = arguments.length;
for (j = 0; j < len; j++) {
stuff = arguments[j];
for (var i in stuff) {
n[i] = stuff[i];
}
}
return n;
}
 
var shape = {
name: 'shape',
toString: function() {return this.name;}
};
var twoDee = {
name: '2D shape',
dimensions: 2
};
var triangle = multi(shape, twoDee, {
name: 'Triangle',
getArea: function(){return this.side * this.height / 2;},
side: 5,
height: 10
});
 
>>> triangle.getArea();//25
>>> triangle.dimensions;// 2
>>> triangle.toString();//"Triangle"
 

你可能感兴趣的:(C++,c,C#,prototype,J#)