javascript 원형 체인 간단 한 예제

2069 단어
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>   </title>
<meta name="description" content="">
<meta name="keywords" content="">
<style type="text/css">
</style>
</head>
<body>
<script type="text/javascript">
	//javascript                  prototype  。
	//    new                ,        
	//               。       (      ,     _proto_)
	//                          
	//                   ,                ,
	//         ,        。

	//     
	function Shape(){
		this.name='Shape';
		this.toString=function(){
			return this.name;
		}
	}
	function TwoDShape(){
		this.name='2D shape';
	}
	function Triangle(side,height) {
		this.name='triangle';
		this.side=side;
		this.height=height;
		this.getArea=function(){
			return this.side*this.height/2;
		}
	}
	//          TwoDShape   prototype   
	//               。          
	//   Shape()        、      ,    
	//TwoDShape()    ,                 
	//     。
	TwoDShape.prototype=new Shape();
	Triangle.prototype=new TwoDShape();
	//  constructor
	TwoDShape.prototype.constructor=TwoDShape;
	Triangle.prototype.constructor=Triangle;
	var my=new Triangle(5,10);
	var area=my.getArea(); //25
	//                , this      my  
	var mystr=my.toString(); // triangle
	my instanceof Shape; //true
	my instanceof TwoDShape //true
	Shape.prototype.isPrototypeOf(my); //true
	TwoDShape.prototype.isPrototypeOf(my); //true
	Triangle.prototype.isPrototypeOf(my); //true
	//            
	//               ,         this  。
	function Shape(){
		this.name="Shape";
	}
	//          new Shape()               
	// name  ,                。
	//    ,        name          ,        
	//          。
	function Shape(){}
	//             ,     。                 
	Shape.prototype.name='Shape';

</script>
</body>
</html>

좋은 웹페이지 즐겨찾기